2013-12-20 71 views
3

考虑以下typeof运算和一个基类

class Base 
    { 
     public int id { get; set; } 
    } 

    class Sub1 : Base 
    { 
     public int x { get; set; } 
     public int y { get; set; } 
    } 

    class Sub2 : Base 
    { 
     public string x { get; set; } 
     public string y { get; set; } 
    } 

    class Wrapper 
    { 
     public int x { get; set; } 
     public Sub1 sub1 { get; set; } 
     public Sub2 sub2 { get; set; } 
    } 

什么,我试图做的是下面的,我有这样的效用函数,从这个函数得到CLR类型

private static Dictionary<Type, SqlDbType> types; 
    public static SqlDbType GetSqlDbType(Type type, string propertyName) 
    { 
     if (types == null) 
     { 
      types = new Dictionary<Type, SqlDbType>(); 
      types.Add(typeof(Int32), SqlDbType.Int); 
      types.Add(typeof(Int32?), SqlDbType.Int); 
      types.Add(typeof(decimal), SqlDbType.Decimal); 
      //etc 
      //the problem is here i want to return SqlDbType.VarBinary for every class that inherits Base 
      types.Add(typeof(Base), SqlDbType.VarBinary); 
     } 
     return types[type]; 
    } 

SQL类型如果类型是从Base类继承的,我想返回SqlDbType.VarBinary,这可能吗?

+4

尝试IsAssignableFrom() – Liath

回答

1

字典中的类型似乎是所有值类型,不受继承的影响。即使您将string添加到SqlDbType.NVarChar映射中,情况仍然如此。正因为如此,你可以简单地做:

private static Dictionary<Type, SqlDbType> types; 

public static SqlDbType GetSqlDbType(Type type, string propertyName) 
{ 
    if (types == null) 
    { 
     types = new Dictionary<Type, SqlDbType>(); 
     types.Add(typeof(Int32), SqlDbType.Int); 
     types.Add(typeof(Int32?), SqlDbType.Int); 
     types.Add(typeof(decimal), SqlDbType.Decimal); 
     // etc 
    } 

    SqlDbType result; 

    if (types.TryGetValue(type, out result)) 
    { 
     return result; 
    } 
    else 
    { 
     return SqlDbType.VarBinary; 
    } 
} 

或者,你可以做

if (types.TryGetValue(type, out result)) 
    { 
     return result; 
    } 
    else if (typeof(Base).IsAssignableFrom(type)) 
    { 
     return SqlDbType.VarBinary; 
    } 
    else 
    { 
     // whatever, for example: 
     throw new ArgumentException(type); 
    } 
6

是的,但它会比你的例子更复杂一点。一个简单的例子:

typeof(int?).IsAssignableFrom(typeof(int)) 

的IsAssignableFrom方法可以让你检查是否有两个类型之间的隐式转换 - 在继承的类的情况下,这是一个给定的。所以,你可以说

typeof(Base).IsAssignableFrom(type) 

然而,正如你所看到的,这意味着你不能使用词典的类型了 - 你必须单独检查每一个可能性,并以正确的顺序。最简单的方法是将某些类型视为简单(字典查找),另一些视为支持继承(基本类型列表)。

相关问题