c# – typeof和Base类
发布时间:2020-12-16 01:59:05 所属栏目:百科 来源:网络整理
导读:考虑以下 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
考虑以下
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.VarBinary如果类型是从Base类继承的,这可能吗? 解决方法
字典中的类型似乎是所有值类型,不受继承的影响.即使您向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); } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |