本文介绍了C#委托逆变与lambda表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

第二个测试方法,下面不编译(不能转换lambda表达式到目标类型 D1 )。这是否意味着(非通用)委托逆变不lambda表达式的工作?



  [的TestFixture] 
公类MyVarianceTests
{
私人抽象类动物{}
私有类虎:动物{}

私人委托类型D1(虎);

私有静态类型M1(兽兽)
{
返回animal.GetType();
}

[测试]
公共无效ContravariantDelegateWithMethod()
{
D1 FUNC = M1;
型结果= FUNC(新虎());
Assert.AreEqual(结果的typeof(虎));
}

[测试]
公共无效ContravariantDelegateWithLambda()
{
D1 FUNC =(兽兽)=> animal.GetType();
型结果= FUNC(新虎());
Assert.AreEqual(结果的typeof(虎));
}
}


解决方案

您'已经确定了语言的不一致性。



这是在的:



...which raises the question:

Why didn't the language designers bother supporting this feature?

<speculation>

Clearly, the feature has some small benefits. But does it justify the costs of the extra complications required in a compliant compiler implementation?

When you write a lambda expression, you must already know exactly which delegate/expression-tree type it is being converted to (there's no general-purpose type that can "hold" an arbitrary lambda). As of C# 5, a lambda (in contrast to a method) serves absolutely no purpose other than to help in the creation of a single delegate / expression-tree instance. Consequently, there's no advantage (other than convenience) to explicitly specifying a more general type than required for a parameter and expecting contra-variance support from the compiler. You could just omit the type completely and rely on type-inference (or, worst case, explicitly specify the exact parameter-type required) without any loss in reusability or expressibility.

This obviously doesn't apply to methods, which serve other purposes other than the creation of delegates/expression-trees. You may desire a particular function signature (different from the delegate's) because it is the most appropriate, or require it because it must satisfy an interface contract. Further more, consider that you (as the programmer creating the delegate/expression-tree) don't necessarily "own" the method in question (it could be in a third-party assembly) when you are performing a method-group conversion. This is never the case with lambdas.

It appears the language-designers felt the benefits of implementing contra-variance of parameter types for lambdas didn't justify the costs, unlike for method-groups.

</speculation>

这篇关于C#委托逆变与lambda表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 13:01