In c#, why can't lambdas have extensions?

后端 未结 2 1655
梦谈多话
梦谈多话 2020-12-19 17:51

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

public static class HandyExtensions
{
public static IEnumerator Tweeng( this System.Action v, float d )
             


        
相关标签:
2条回答
  • 2020-12-19 18:31

    Quell your tears fair Joe, let not despair drive you from your dream! If you explicitly cast it, it should work. Try:

    yield return StartCoroutine(
            ((System.Action<float>)( (x)=>laser=x )).Tweeng(3.141f)
        );
    
    0 讨论(0)
  • 2020-12-19 18:48

    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.

    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.

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

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

    0 讨论(0)
提交回复
热议问题