将 PropertyInfo.PropertyType 转换为枚举

Casting PropertyInfo.PropertyType to enum

我有一个通用函数,可以使用反射从 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 吗?或者我是否需要为我定义的 enums 编写一个特殊的转换函数。

编辑: 我得到

"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());

你得到 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);

我的class是这样的

public enum Status
{
    Active,
    Deactive
}

public class Sample
{
    public long Id{ get; set; }
    public string Name{ get; set; }
    public Status UserStatus{ get; set; }
}

在数据库中,我将 Status="Active" 存储为字符串。 我使用了您的解决方案,但出现以下错误

System.ArgumentException: 'The value passed in must be an enum base or an underlying type for an enum, such as an Int32. Parameter name: value'