在C#中,为什么Lambda不能具有扩展名? [英] In c#, why can't lambdas have extensions?

查看:60
本文介绍了在C#中,为什么Lambda不能具有扩展名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Unity中,这是c#中的一个类别,

In Unity, here's a category in c#,

public static class HandyExtensions
{
public static IEnumerator Tweeng( this System.Action<float> v, float d )
    {
    while (..)
        {
        ..
        v( 13f*t );
        yield return null;
        }
    v(13f);
    }

编译正常!

但是,如果您尝试使用它,

But if you try to use it,

yield return StartCoroutine(
            ( (x)=>laser=x ).Tweeng(3.141f)
        );

出现此添加错误:

资产/脚本/...cs(116,34):错误CS0023:.' operator cannot be applied to operand of type匿名方法'

对此我有泪.

C#如何让我们失望?

How could c# let us down?

肯定有一种方法可以像这样调用lambda进行扩展吗?

Surely there's a way to call "on" a lambda like that, for an extension?

顺便说一句,解决方法是去3.14f.Tweeng((x)=>laser=x),但它不那么酷.

BTW the workaround is to go 3.14f.Tweeng((x)=>laser=x) but it's not as cool.

推荐答案

很抱歉,这使您感到难过,但这种选择是语言设计团队故意做出的.评估给定扩展方法是否有效的代码要求接收者具有明确的类型,而lambda表达式则没有类型.

I'm sorry this saddens you, but this choice was made deliberately by the language design team. The code which evaluates whether a given extension method is valid requires that the receiver have a clear type, and lambda expressions do not have a type.

关于这一点,存在一些争论,但是最终决定(1)如果像lambda,方法组和null文字之类的无类型表达式成为扩展方法的接收者,则建议的功能可能会造成混淆或容易出错. (2)提议的功能完全不需要使LINQ正常工作.实施C#3时,我们的时间表非常有限,削减了使LINQ正常工作所需的所有内容.设计,实现和测试不允许lambda作为接收器"的功能要比考虑将lambda,方法组或null用作接收器的所有潜在奇数情况要容易得多.

There was some debate on this point, but ultimately it was decided that (1) the proposed feature is potentially confusing or error-prone if typeless expressions like lambdas, method groups and null literals get to be receivers of extension methods, and (2) the proposed feature is not at all necessary to make LINQ work. We were very constrained in our schedules when implementing C# 3 and anything that was not necessary to make LINQ work was cut. It was much easier to design, implement and test the feature of "don't allow lambdas as receivers" than to have to consider all the potentially odd cases where a lambda, method group or null was being used as the receiver.

正如其他人所说,您可以简单地转换lambda,或将其放入变量中,然后将其用作接收方.

As others have said, you can simply cast the lambda, or put it in a variable and then use the variable as the receiver.

或者,如您所述,您可以考虑在特定示例中将float用作接收器.

Alternatively, as you note, you could consider using the float as the receiver in your specific example.

这篇关于在C#中,为什么Lambda不能具有扩展名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆