C# typeof和基类
考虑以下几点C# typeof和基类,c#,C#,考虑以下几点 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; }
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 GetSqlDbType(类型类型,字符串属性名称)
{
如果(类型==null)
{
类型=新字典();
Add(typeof(Int32),SqlDbType.Int);
Add(typeof(Int32?),SqlDbType.Int);
Add(typeof(decimal),SqlDbType.decimal);
//等
//问题在于,我想为继承Base的每个类返回SqlDbType.VarBinary
Add(typeof(Base),SqlDbType.VarBinary);
}
返回类型[类型];
}
从这个函数中,我想返回SqlDbType.VarBinary,如果类型是从基类继承的,这可能吗?是的,但是它比您的示例要复杂一点。一个简单的例子:
typeof(int?).IsAssignableFrom(typeof(int))
IsAssignableFrom方法将允许您检查这两种类型之间是否存在隐式强制转换——对于继承的类,这是一个给定的类型。所以你可以说
typeof(Base).IsAssignableFrom(type)
然而,正如你所看到的,这意味着你不能再使用字典来查找这些类型了——你必须分别检查每一种可能性,并且按照正确的顺序进行检查。最简单的方法是将某些类型视为简单类型(字典查找),而将某些类型视为支持继承类型(基类型列表)。字典中的类型似乎都是值类型,不受继承影响。即使在
SqlDbType.NVarChar
映射中添加string
,这仍然是正确的。因此,您可以简单地执行以下操作:
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;
}
}
请从()尝试IsAssignableFrom
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);
}