使用逆变器时,我正在尝试使以下内容正常工作和挣扎。我的理解是协方差是您可以从基类型返回派生类型的地方。逆变是您可以将派生类型从基类型作为参数传递给类的地方。
所以我有以下接口(逆变):
public interface IBase<in T> where T: BaseModel
{
void Process(T model);
}
然后我有一个抽象类
public abstract class Base<T>: IBase<T> where T: BaseModel
{
public virtual void Process(T model)
{
// throw new System.NotImplementedException();
}
}
和另一个具体的类
public class Parent: Base<ParentModel>
{
public override void Process(ParentModel model)
{
// throw new System.NotImplementedException();
}
}
考虑到泛型类型仅用作输入而不是返回类型,我不明白为什么我不能执行以下操作:
IBase<BaseModel> baseContravariant = new Parent();
// This doesn't compile. I will eventually have a list of IBase<BaseMode> to which I'd like to pass in different parent instances.
我有另一个使用协方差的例子,它在下面并且工作正常。
public interface IBase<out T> where T : BaseModel, new()
{
T ProcessAndGet();
}
抽象的
public abstract class Base<T>: IBase<T> where T: BaseModel, new()
{
public virtual T ProcessAndGet()
{
var result = new T() as BaseModel;
// More shizzle here
return (T)result;
}
}
具体的
public class Parent : Base<ParentModel>
{
public override ParentModel ProcessAndGet()
{
var x = base.ProcessAndGet();
return x;
}
}
现在我可以做
IBase<BaseModel> baseInstance = new Base<BaseModel>();
IBase<BaseModel> derived = new Parent();
baseInstance = derived;
上面的示例还有更多代码,但为了便于阅读,我已将其删除(希望如此!):-)