如何最简洁地访问Action(或Func)属性的参数?

kdb*_*man 0 c# lambda properties

我很惊讶我无法在stackoverflow或MSDN上找到这个问题的答案.我强烈怀疑我的搜索技巧是这里的差距,但无论如何我都会冒险.我在stackoverflow 上看了 三个 帖子.这些都不是我所要求的直接问题或答案,但它们相关性很大,我希望无论如何都要从中收集答案.但没有运气!无论如何,这是问题!


当我定义一个声明Action<int, int>属性的接口时

public interface ICoordinateProcessor {
    System.Action<int, int> onTwoIntegers { get; }
}
Run Code Online (Sandbox Code Playgroud)

它可以使用返回null的lambda轻松实现,并将两个整数作为参数

public class RealCoordinateProcessor : ICoordinateProcessor {
    public override Action<int, int> onTwoIntegers {
        get {
            return (x, y) => this.someInternalState = x + y;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

十分简单!但是当我使用roslyn自动完成界面时,它会填写以下内容:

public class RealCoordinateProcessor : ICoordinateProcessor {
    public override Action<int, int> onTwoIntegers => throw new NotImplementedException();
}
Run Code Online (Sandbox Code Playgroud)

编译没有错误或警告,也是我从未见过并且更喜欢使用的非常简洁的语法. 如何使用更严格的语法来获得与上面第二个片段相同的效果?

或者等效地,如何在第三个片段中访问lambda的参数? 当我尝试这个:

public override Action<int, int> onTwoIntegers (x, y) => throw new NotImplementedException();
Run Code Online (Sandbox Code Playgroud)

编译器吓坏了,因为我显然不知道我在做什么.但我不确定还有什么可以尝试,而且我不确定如何搜索示例.

小智 5

现在,在Roslyn的C#6中,您可以使用Expression Bodied Function Members:

public override Action<int,int> onTwoIntegers => (x,y) => { };
Run Code Online (Sandbox Code Playgroud)

通常,与delegate-lambda语法没有太大区别:

var onTwoIntegersClass = new RealCoordinateProcessor().onTwoIntegers;
Action<int,int> onTwoIntegersVar = (x,y)=>{};
Delegate.Combine(onTwoIntegersVar, onTwoIntegersClass);
Run Code Online (Sandbox Code Playgroud)