C# 泛型继承与转换

C# 泛型继承与转换,c#,generics,inheritance,C#,Generics,Inheritance,我有以下课程: class Item { } class MeetingItem : Item { } class ItemGroup<T> { } 但是,这一点失败了: ItemGroup<Item> itemGroup; itemGroup = new ItemGroup<MeetingItem>(); // Fails here 这似乎有点老套,但很管用。我有点担心ItemType属性的性能,我愿意接受任何重构想法。这是一个有差异的问题 考虑这样一个

我有以下课程:

class Item { }
class MeetingItem : Item { }
class ItemGroup<T> { }
但是,这一点失败了:

ItemGroup<Item> itemGroup;
itemGroup = new ItemGroup<MeetingItem>(); // Fails here

这似乎有点老套,但很管用。我有点担心ItemType属性的性能,我愿意接受任何重构想法。

这是一个有差异的问题

考虑这样一个简单的界面:

List<ItemGroup> groups = new List<ItemGroup>();
groups.Add(new ItemGroup(typeof(MeetingItem));
interface MyInterface<T>
{
  T GetStuff();
  void SetStuff(T value);
}
另一方面,对于逆变:

Func<string> func = () => new object(); // Error, Func<T> isn't contravariant
Action<string> func = (object val) => { ... }; // Safe, Action<T> is contravariant
Func=()=>newobject();//错误,Func不是逆变的
动作func=(对象值)=>{…};//安全,行动是相反的

你应该看看协方差和逆变:这里的解释是:仅仅因为两种类型,
a
B
有一个特定的继承关系,这并不意味着
G
G
有相同的继承关系。好的。。。很公平。。。我不能那样做。我现在明白了。所以,问题是,我应该删除这个问题,还是留下它,让它将人们重定向到副本?或者我应该把卢安的答案标记为答案,还是让它保持开放状态?我建议重新打开它,把我(希望如此)的最终答案放进去。它涉及到使用一个非泛型类(ArrayList),我将该类继承到自己的类中。我认为它会起作用,可能会帮助其他人。我想保留对副本的引用,但是这也会帮助其他人。
groups[0].ItemType == typeof(MeetingItem)
interface MyInterface<T>
{
  T GetStuff();
  void SetStuff(T value);
}
IEnumerable<object> enumerable = Enumerable.Empty<string>(); // Safe, 
                                                             // enumerable is covariant
ICollection<object> collection = new Collection<string>();   // Error, 
                                                             // collection isn't covariant

Func<object> func = () => "Hi!"; // Safe, Func<T> is covariant
Action<object> func = (string val) => { ... }; // Error, Action<T> isn't covariant
Func<string> func = () => new object(); // Error, Func<T> isn't contravariant
Action<string> func = (object val) => { ... }; // Safe, Action<T> is contravariant