【问题标题】:Create a list of types in C#在 C# 中创建类型列表
【发布时间】:2012-10-27 23:55:11
【问题描述】:

我想创建一个类型列表,每个类型都必须实现一个特定的接口。喜欢:

interface IBase { }
interface IDerived1 : IBase { }
interface IDerived2 : IBase { }

class HasATypeList
{
    List<typeof(IBase)> items;
    HasATypeList()
    {
        items.Add(typeof(IDerived1));
    }

}

所以我知道我可以做到

List<Type> items;

但这不会将列表中允许的类型限制为实现 IBase 的类型。我必须编写自己的列表类吗?不是说这有什么大不了,但如果我不必……

【问题讨论】:

  • 我以为我有答案,但你是对的——你不想要一个 IBase 实现对象的列表,你想要一个实现该接口的 TYPE 列表。我认为您必须在 Add 中使用额外的逻辑来实现自己的列表

标签: c# reflection collections


【解决方案1】:

typeof(IBase)typeof(object)typeof(Foo),都返回一个Type的实例,具有相同的成员等等。

我看不出您想要达到什么目的,以及为什么要区分这些?

其实你这里写的代码:

List<typeof(IBase)> items;

(我什至不知道这是否编译?) 和这个完全一样:

List<Type> items;

所以事实上,你想要达到的目的是没有用的。

如果你真的想实现这个 - 但我不明白为什么...... - 你可以像 Olivier Jacot-Descombes 建议的那样创建自己的集合类型,但在这种情况下,我宁愿创建一个而是继承自 Collection&lt;T&gt; 的类型:

public class MyTypeList<T> : Collection<Type>
{
    protected override InsertItem( int index, Type item )
    {
        if( !typeof(T).IsAssignableFrom(item) )
        {
            throw new ArgumentException("the Type does not derive from ... ");
        }

        base.InsertItem(index, item);
    }
}

【讨论】:

  • 这基本上就是我最终要做的。我只是想知道是否有更聪明的方法来做到这一点。例如使用 where 子句之类的......
  • 而且我不认为它没用。我想要一个类型列表,其中列表中的所有类型都必须实现某个接口。
  • 你打算用那个列表做什么?
【解决方案2】:

是的。如果 type 不是 IBase 的子类,您必须实现一个抛出异常的 List。

没有内置的方法可以做你想做的事。

【讨论】:

    【解决方案3】:

    唯一的办法就是创建自己的类型集合

    public class MyTypeList
    {
        List<Type> _innerList;
    
        public void Add(Type type)
        {
            if (typeof(IBase).IsAssignableFrom(type)) {
                 _innerList.Add(type);
            } else {
                throw new ArgumentException(
                    "Type must be IBase, implement or derive from it.");
            }
        }
    
        ...
    }
    

    【讨论】:

      猜你喜欢
      • 2019-07-27
      • 2016-02-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多