【问题标题】:Accept only types, which declaring some interface只接受声明一些接口的类型
【发布时间】:2016-01-01 05:37:10
【问题描述】:

如何做这样的事情

List<Type:IMyInterface> a = new List<Type:IMyInterface>;
a.Add(typeof(MyClass1)); //MyClass1..3 implementing IMyInterface
a.Add(typeof(MyClass2));
a.Add(typeof(MyClass3));
IMyInterface c = default(a[1]); //create MyClass2 object
a.Add(typeof(Object)); //must fail

不先构造对象或稍后检查类型?

【问题讨论】:

  • default(a[1]) 将始终返回null,您需要更好地详细说明用例。
  • default(Type t) 必须返回使用默认无参数构造函数创建的对象(如果存在)。在我的情况下,Type t 可以是 typeof(MyClass1..3)
  • 什么应该只接受类型,为什么?你想做什么?
  • default(a[1]) 甚至不会被编译(为什么不Activator.CreateInstance ?)。我建议实现您自己的集合聚合List&lt;Type&gt; 并在添加之前验证类型。

标签: c# oop types interface


【解决方案1】:

C# 不直接支持你想要的。因为 Type 参数的约束只能在构造函数、继承层次结构、接口实现和其他一些上指定。 more details

你可以用不同的方式来做,但是在这种方法中没有编译时错误:

公共接口IMyConstraint { 无效做(); }

public class MyClass: IMyConstraint
{
    public void Do()
    {
    }
}

// Inherit from the List class to add some functionality to it
public class MyTypeList<T> : List<T> where T : System.Type
{
    public MyTypeList()
    {

    }

    // use new keyword to prevent client from using the List.Add method.
    public new void Add(T type)
    {
        // here you check if the type is implementing the interface or not
        if (!typeof(IMyConstraint).IsAssignableFrom(type))
        {
            // if it dose not implement the interface just throw an exception
            throw new InvalidOperationException();
        }
        // call the original List.Add method            
        base.Add(type);
    }
}

【讨论】:

  • 谢谢。这是完整的答案。
【解决方案2】:

如果您知道静态涉及的类型,则可以这样做:

public class TypeList<T>
{
    private readonly List<Type> types = new List<Type>();
    public void Add<D>() where D : T, new()
    {
        this.types.Add(typeof(D));
    }

    public T NewAt(int index)
    {
        return (T)Activator.CreateInstance(this.types[index]);
    }
}

那么你可以这样做:

var a = new TypeList<IMyInterface>;
a.Add<MyClass1>();
a.Add<MyClass2>();
a.Add<MyClass3>();
IMyInterface c = a.NewAt(1);
a.Add<object>(); //won't compile

【讨论】:

    猜你喜欢
    • 2017-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-16
    • 2014-09-22
    • 1970-01-01
    • 2014-05-09
    • 2018-02-19
    相关资源
    最近更新 更多