c# - 存储通用对象的列表/字典

标签 c# list generics dictionary covariance

我想知道是否有办法存储在 Dictionary/List/... 中属于通用类型。

让我们想象一下这个类:

public class Registry{
    private Dictionary<String, MyGenericType<IContainableObject>> m_elementDictionary = new Dictionary<String, MyGenericType<IContainableObject>>();

    public void Register<T>(MyGenericType<T> objectToRegister)
    where T: IContainableObject
    {
        m_elementDictionary[objectToRegister.key] = objectToRegister; //This doesn't work
    }
}

我不明白为什么我们不能将此元素添加到 Dictionary因为我们知道我们收到的泛型参数实际上是一个 MyGenericType<IContainableObject>由于 where 条件。

请注意:

  1. 我知道我可以在 MyGenericType<IContainableObject> 上放置一个接口(interface)一个商店这个的字典。这是主题。
  2. 我知道我可以有一个 MyGenericType<IContainableObject>争论,这也是重点。

我更关心的是协变/逆变是否对这里有帮助?

最佳答案

你应该像这样表达 where 条件:

public void Register<T>(T objectToRegister)
    where T : MyGenericType<IContainableObject> {
    m_elementDictionary[objectToRegister.key] = objectToRegister;
}

此外,您应该将 MyGenericType 定义为协变的,如本例所示:

interface IContainableObject { 
}

public interface MyGenericType<out T> {
    string key();
}

interface IDerivedContainableObject : IContainableObject {
}

class Program {

    private static Dictionary<String, MyGenericType<IContainableObject>> m_elementDictionary = new Dictionary<String, MyGenericType<IContainableObject>>();

    public static void Register<T>(T objectToRegister)
        where T : MyGenericType<IContainableObject> {
            m_elementDictionary[objectToRegister.key()] = objectToRegister;
    }

    static void Main(string[] args) {
        MyGenericType<IDerivedContainableObject> x = null;
        MyGenericType<IContainableObject> y = x;
        Register(y);
    }

}

(注意 MyGenericType 现在是一个接口(interface))

关于c# - 存储通用对象的列表/字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28062171/

相关文章:

java - 使用 Enum 作为 Map 中的类型时的奇怪行为

java - 当运行时类型也是泛型类型时,将方法引用用作期望与泛型类型接口(interface)的方法的 lambda 时出现编译器错误

c# - 如何将控件的属性绑定(bind)到另一个控件的属性?

list - 通过函数参数访问 R 列表元素

list - 获取两个列表元素的所有可能组合的元组列表的 Pythonic 方法是什么?

list - Erlang:将两个列表相乘

android - Kotlin 属性 : "Type parameter of a property must be used in its receiver type"

c# - MySQL 语法错误 ASP.NET

javascript - Unity C# 如何正确加载托管 DLL?

c# - 在初始化后的事件定义中,为什么我会收到错误 18 使用未分配的局部变量 'beforeEvntDrawArg'