代码之家  ›  专栏  ›  技术社区  ›  hunter

将SqlDataType转换为C#枚举

  •  2
  • hunter  · 技术社区  · 14 年前

    这是自动进行1-1 Table.Column-Class.Property匹配的过程的一部分。我试着把每种可能的碱基类型 listed here . 我已经越来越多地使用ORM,但是现在我回到了一个他们正在做的环境中 Id = row["Id"] as int 但我并没有用那种暴力的方式来进行强制转换,而是在属性上使用属性,这样我就可以编写 DataTable.ExtractAs<MyClass> 它试图创造和 IList<MyClass> 基于这些属性。

    我的问题是:有没有更好的方法来处理从SqlDataType到覆盖所有整型的C#enum的转换?

    现在我要做的是:

    internal static bool TrySetValue<T>(T t, PropertyInfo property, DataRow row, string columnName)
    {
        Type propertyType = property.PropertyType;
    
        // other logic and unique cases
    
        if (propertyType.IsEnum 
            && Enum.GetUnderlyingType(propertyType) == value.GetType())
        {
            property.SetValue(t, value, null);
            return true;
        }
    }
    

    是不是太过分了?有更好的办法吗?我看不到里面有人 PropertyInfo 解决了这些整数类型的问题。

    1 回复  |  直到 14 年前
        1
  •  2
  •   Julien Lebosquain    14 年前

    你可以用 Enum.ToObject(object) 它将处理 SByte , Byte , Int16 , UInt16 , Int32 , UInt32 , Int64 UInt64 到枚举:

    if (propertyType.IsEnum) {
        property.SetValue(Enum.ToObject(value));
    }