【发布时间】:2019-12-14 10:00:57
【问题描述】:
我在尝试添加具有不同签名的两种方法时看到了非常奇怪的行为(它们之间是协变的)。当我尝试添加第二种方法时,它会抛出一个ArgumentException: Incompatible Delegate Types。
public class SomeClass { } // Just a class that inherits from object
public interface GenericInterface<out T> { // An interface with a covariant parameter T
event System.Action<T> doSomethingWithT;
}
public interface SpecificInterface : GenericInterface<SomeClass> { } // A more specific interface where T = SomeClass
public class ImpClass: SpecificInterface { // An implementation of the more specific interface
public event System.Action<SomeClass> doSomethingWithT;
}
基本上是一个简单的泛型接口,其中泛型参数是协变的,一个为泛型分配类型的子接口,以及一个子接口的实现。
这是引发异常的代码:
protected void Start() {
ImpClass impObj = new ImpClass();
GenericInterface<object> genericObj = impObj; // assignment possible because interface is covariant
impObj.doSomethingWithT += DoSomethingSpecific;
genericObj.doSomethingWithT += DoSomething; // this line throws an exception
}
protected void DoSomething(object o) { }
protected void DoSomethingSpecific(SomeClass o) { }
现在代码编译得很好,并且只添加更具体或更通用的方法,每个方法都可以单独工作,但如果我尝试同时添加两者,我会得到异常。
没有意义。知道为什么吗?有什么解决办法吗?
【问题讨论】:
-
我假设
CovClass是ImpClass? (错字) -
@JuanR 是的,正在修复
标签: c# covariance