我将我的类层次结构定义为Object-> Fruit-> Apple
class Fruit : object{}
class Apple : Fruit{}
并创建了两个静态方法来处理这些类
static Fruit FruitProcessor(string fruit)
{
return new Fruit();
}
static Apple ApplesProcessor(string apple)
{
return new Apple();
}
现在我宣布一个代表没有任何 in, out
关键字
public delegate TResult Funk<T, TResult>(T arg);
在我的代码中,我做了以下任务:
Funk<string, Fruit> myFunc;
myFunc = FruitProcessor; // ok, we match signature exactly
myFunc = ApplesProcessor;// this should not work, but works
由于我没有将TResult声明为协变out
参数,因此不应该将ApplesProcessor
指定给myFunc
委托。但这是可能的,程序编译和执行没有任何错误。
如果我更改Funk签名以添加out TResult
public delegate TResult Funk<T, out TResult>(T arg);
一切都和以前一样。
怎么可能?
答案 0 :(得分:2)
这样的情况由通常的隐式转换处理。引用相关的MSDN页面(https://msdn.microsoft.com/en-us/library/dd233060.aspx):
public class First { }
public class Second : First { }
public delegate First SampleDelegate(Second a);
public delegate R SampleGenericDelegate<A, R>(A a);
// Matching signature.
public static First ASecondRFirst(Second first)
{ return new First(); }
// The return type is more derived.
public static Second ASecondRSecond(Second second)
{ return new Second(); }
// The argument type is less derived.
public static First AFirstRFirst(First first)
{ return new First(); }
// The return type is more derived
// and the argument type is less derived.
public static Second AFirstRSecond(First first)
{ return new Second(); }
// Assigning a method with a matching signature
// to a non-generic delegate. No conversion is necessary.
SampleDelegate dNonGeneric = ASecondRFirst;
// Assigning a method with a more derived return type
// and less derived argument type to a non-generic delegate.
// The implicit conversion is used.
SampleDelegate dNonGenericConversion = AFirstRSecond;
// Assigning a method with a matching signature to a generic delegate.
// No conversion is necessary.
SampleGenericDelegate<Second, First> dGeneric = ASecondRFirst;
// Assigning a method with a more derived return type
// and less derived argument type to a generic delegate.
// The implicit conversion is used.
SampleGenericDelegate<Second, First> dGenericConversion = AFirstRSecond;
简而言之,在您的确切情况下,您将非泛型委托分配给泛型委托 - 在这种情况下始终使用隐式转换。要真正使代码失败,您需要执行以下操作:
Funk<string, Fruit> myFunc;
Funk<string, Apple> myAppleFunc = ApplesProcessor;
myFunc = FruitProcessor;
myFunc = myAppleFunc; // Undefined implicit conversion on generic delegate
答案 1 :(得分:2)
根据MSDN代理返回类型的协方差和委托输入类型的逆变,暗示自.NET 3.5。因此,向您的委托添加in
和out
没有任何区别。
添加这个的一个原因是你可以分配一个&#34;香草&#34;事件处理程序,它接受EventArgs
参数到多个事件,这些事件可能使用派生自EventArgs
的更具体的类。例如,您可以使用相同的委托处理按钮单击和按键,即使前者传递MouseEventArgs
参数,而后者传递KeyEventArgs
参数。