gpt4 book ai didi

c# - 将 PropertyInfo.PropertyType 转换为枚举

转载 作者:行者123 更新时间:2023-11-30 15:26:50 28 4
gpt4 key购买 nike

我有一个通用函数,可以使用反射从 DataRow 创建对象。我正在使用此函数从 Access 数据库导入表:

private static T CreateItemFromRow<T>(DataRow row, IList<PropertyInfo> properties) where T : new()
{
T item = new T();
foreach (var prop in properties)
{
try
{
if (prop.PropertyType.IsEnum)
prop.SetValue(item, row[prop.Name], null); // what to do??
else
prop.SetValue(item, row[prop.Name], null);
}
catch (Exception ex)
{
System.Diagnostics.Debug.Assert(false, string.Format("failed to assign {0} a value of {1}", prop.Name, row[prop.Name]));
}
}
return item;
}

我遇到的问题是属性类型是 enum。我试过使用 Enum.Parse,但没有成功(我无法编译任何东西)。

有什么方法可以使用我的函数将 row[prop.Name] 表示的对象转换为正确的 enum 吗?或者我是否需要为我定义的 enum 编写一个特殊的转换函数。

编辑:我得到了

"the type or namespace prop could not be found. Are you missing an assembly directive or reference" compile error for the following:

var val = (prop.PropertyType)Enum.Parse(typeof(prop.PropertyType), row[prop.Name].ToString());

最佳答案

The reason for the type or namespace prop could not be found 你得到的异常是因为你不能以这种方式转换为类型 (prop.PropertyType)Enum.Parse(typeof (prop.PropertyType) - 您只能在编译时知道类型的情况下执行此操作 - (SomeEnum)Enum.Parse(typeof(SomeEnum)

正确的做法是在设置属性值之前获取枚举值:

prop.SetValue(item, Enum.ToObject(prop.PropertyType, row[prop.Name]), null);

关于c# - 将 PropertyInfo.PropertyType 转换为枚举,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28502604/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com