【问题标题】:How do you manage a C# Generics class where the type is a container of a base class?您如何管理类型是基类容器的 C# 泛型类?
【发布时间】:2011-06-11 04:12:56
【问题描述】:

我收到以下错误

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

对于以下类:

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

我做错了什么?

干杯

【问题讨论】:

    标签: c# generics collections


    【解决方案1】:

    您正在尝试分别使用MyContainer&lt;A&gt;MyContainer&lt;B&gt; 调用myList.Add。两者都不能转换为MyContainer&lt;MyBase&gt;,因为具有不同泛型类型参数的两个泛型实例始终是不相关的,即使类型参数是相关的也是如此。

    做到这一点的唯一方法是创建一个IMyContainer&lt;out T&gt; 协变通用接口。如果A 派生自MyBase,这将允许您将IMyContainer&lt;A&gt; 转换为IMyContainer&lt;MyBase&gt;。 (注意:只有接口可以有协变和逆变类型参数,这仅在 .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();
        }
    }
    

    【讨论】:

    • +1 您应该补充一点,这仅在 .NET4 中可用(无论随附的 C# 版本是什么)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-22
    • 2018-01-13
    • 1970-01-01
    相关资源
    最近更新 更多