当尝试添加具有不同签名的两种方法(彼此是协变的)时,我看到非常奇怪的行为。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) { }
现在代码可以正常编译,并且仅添加更具体的方法或仅添加更通用的方法,每个方法都可以单独正常工作,但如果我尝试添加两者,则会出现异常。
没有道理。知道为什么吗?以及有什么解决办法吗?
慕姐8265434
沧海一幻觉
相关分类