考虑以下
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类继承的,这可能吗?
答案 0 :(得分:6)
是的,但它会比你的例子复杂一点。一个简单的例子:
typeof(int?).IsAssignableFrom(typeof(int))
IsAssignableFrom方法将允许您检查两种类型之间是否存在隐式转换 - 在继承类的情况下,这是给定的。所以你可以说
typeof(Base).IsAssignableFrom(type)
然而,正如您所看到的,这意味着您不能再使用字典作为类型 - 您必须单独检查每个可能性,并按正确的顺序。最简单的方法是将某些类型视为简单(字典查找),将某些类型视为支持继承(基类型列表)。
答案 1 :(得分: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);
}