考虑以下
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类型获取sql类型
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]; }
解决方法
字典中的类型似乎是所有值类型,不受继承的影响.即使您向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); }