我想知道是否有办法存储在 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 条件。
请注意:
- 我知道我可以在
MyGenericType<IContainableObject>
上放置一个接口(interface)一个商店这个的字典。这是主题。 - 我知道我可以有一个
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/