早些时候,我对接口的变化有很好的理解。现在我对变体接口中代表的变化有点困惑。方法、属性、索引器和事件可以在接口中定义。变体接口中的方法、属性和索引器的签名是直接的。事情发生了逆转。
我不明白为什么返回值的方法在协变接口中起作用,但委托的类似签名不起作用。一个不应该返回任何东西的逆变委托是有效的。逆变接口也是如此。
namespace ConsoleApp1
{
delegate T MyDelegateReturn<out T>();
delegate void MyDelegateTake<in T>(T t);
interface IMyInterfaceReturn<out T>
{
T MyMethodReturn(); //signature with return value and interface with keyword out - ok
//event MyDelegateReturn<T> MyEventReturn; //delegate signature with return value but is error CS1961
event MyDelegateTake<T> MyEventTake; //delegate signature with take parameter but why it is work?
}
interface IMyInterfaceTake<in T>
{
void MyMethodTake(T t); //signature with take argument and interface with keyword in - ok
//event MyDelegateTake<T> MyEventTake; //delegate signature with take parameter but is error CS1961
event MyDelegateReturn<T> MyEventReturn; //delegate signature with return value but why it is work?
}
class MyClass<T> : IMyInterfaceReturn<T>, IMyInterfaceTake<T>
{
public event MyDelegateTake<T> MyEventTake;
public event MyDelegateReturn<T> MyEventReturn;
public T MyMethodReturn()
{
return default;
}
public void MyMethodTake(T t)
{
}
}
class A
{
}
class B : A
{
}
class Program
{
static void Main(string[] args)
{
B MyMethodReturn()
{
return default;
}
void MyMethodTake(A i)
{
}
MyClass<B> myClass1 = new MyClass<B>();
myClass1.MyEventTake += MyMethodTake;
MyClass<A> myClass2 = new MyClass<A>();
myClass2.MyEventReturn += MyMethodReturn;
}
}
}