繁体   English   中英

您如何管理 C# Generics class 类型是基础 ZA2F2ED4F8EBC2CBB1C21A29DCZ40 的容器?

[英]How do you manage a C# Generics class where the type is a container of a base class?

我收到以下错误

`System.Collections.Generic.List>.Add(MyContainer)' 的最佳重载方法匹配有一些无效的 arguments (CS1502) (GenericsTest)

对于以下 class:

A 和 B 是 MyBase 的子类。

public class GenericConstraintsTest
{

    private MyList<MyContainer<MyBase>> myList = new MyList<MyContainer<MyBase>>();

    public GenericConstraintsTest ()
    {
        MyContainer<A> ca = new MyContainer<A>(new A());

        this.Add<A>(new A());
        this.Add<B>(new B());
    }


    public void Add<S> (S value) where S : MyBase
    {
        MyContainer<S> cs = new MyContainer<S>(value);
        myList.Add(cs);    
    }


    public static void Main()
    {
        GenericConstraintsTest gct = new GenericConstraintsTest();
    }
}

我究竟做错了什么?

干杯

您正在尝试分别使用MyContainer<A>MyContainer<B>调用myList.Add 两者都不能转换为MyContainer<MyBase>因为具有不同泛型类型参数的两个泛型实例总是不相关的,即使类型参数是相关的。

做到这一点的唯一方法是创建一个IMyContainer<out T>协变通用接口。 如果AMyBase派生,这将允许您将IMyContainer<A>转换为IMyContainer<MyBase> (注意:只有接口可以有协变和逆变类型参数,这仅在.Net 4中可用)。

例如:

public interface IMyContainer<out T> { }
public class MyContainer<T> : IMyContainer<T> 
{
    public MyContainer(T value) { }
}
public class MyBase { }
public class A : MyBase { }
public class B : MyBase { }

public class GenericConstraintsTest
{

    private List<IMyContainer<MyBase>> myList = new List<IMyContainer<MyBase>>();

    public GenericConstraintsTest()
    {
        MyContainer<A> ca = new MyContainer<A>(new A());

        this.Add<A>(new A());
        this.Add<B>(new B());
    }


    public void Add<S>(S value) where S : MyBase
    {
        MyContainer<S> cs = new MyContainer<S>(value);
        myList.Add(cs);
    }


    public static void Main()
    {
        GenericConstraintsTest gct = new GenericConstraintsTest();
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM