c# – typeof和Base类

考虑以下

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);
    }

相关文章

目录简介使用JS互操作使用ClipLazor库创建项目使用方法简单测...
目录简介快速入门安装 NuGet 包实体类User数据库类DbFactory...
本文实现一个简单的配置类,原理比较简单,适用于一些小型项...
C#中Description特性主要用于枚举和属性,方法比较简单,记录...
[TOC] # 原理简介 本文参考[C#/WPF/WinForm/程序实现软件开机...
目录简介获取 HTML 文档解析 HTML 文档测试补充:使用 CSS 选...