【问题标题】:Pass a list of types, limiting the types to classes derived from a particular parent, in c#在 c# 中传递类型列表,将类型限制为从特定父级派生的类
【发布时间】:2010-08-13 20:55:15
【问题描述】:

我有一个基于对象类型创建表的面向对象数据库的方法。

我希望能够发送要创建的类型列表,但我希望将它们限制为仅派生自特定基类 (MyBase) 的类。

有没有办法在方法签名中要求这个? 而不是

CreateTables(IList<Type> tables)

我能做点什么吗

CreateTables(IList<TypeWithBaseTypeMyBase> tables)

我知道我可以检查发送过来的每种类型的基类,但如果可能的话,我希望在编译时验证这一点。

有什么建议吗?

【问题讨论】:

    标签: c#-4.0 types derived-types


    【解决方案1】:

    您可以执行以下操作:

    CreateTables(IList<MyBase> tables)
    {
        // GetType will still return the original (child) type.
        foreach(var item in tables)
        {
            var thisType = item.GetType();
            // continue processing
        }
    }
    

    【讨论】:

      【解决方案2】:

      你试过了吗?

      CreateTables(IList<MyBase> tables) 
      

      我想这就是你所要做的。

      【讨论】:

        【解决方案3】:

        为什么不把签名改为:

        CreateTables(IList<BaseType> tables)
        

        【讨论】:

        • 调用方不需要实例化类。为了使用该类型而实例化似乎是一种浪费。
        • 我不确定我是否理解。如果您将 IList 传递给方法,那么我假设列表的元素将是 SomeType 的实例化类。我要说的是,只要所有派生类型都继承自它,就可以使用 BaseType 作为 IList 的类型。
        • 我没有得到对象列表。我正在获取类型列表。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-10-14
        • 2014-04-11
        • 2021-10-25
        • 1970-01-01
        • 2012-05-29
        • 2016-02-26
        相关资源
        最近更新 更多