考虑以下
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); }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。