【问题标题】:How to define variable as lambda function如何将变量定义为 lambda 函数
【发布时间】:2013-02-16 03:52:46
【问题描述】:

(Lambda 函数可能是也可能不是我正在寻找的,我不确定)

基本上我想要完成的是:

int areaOfRectangle = (int x, int y) => {return x * y;};

但它给出错误:“无法将 lambda 表达式转换为类型 'int',因为它不是委托类型”

更详细的问题(确实与问题无关,但我知道有人会问)是:

我有几个从重写的 OnLayout 分支出来的函数,以及每个函数都依赖的几个函数。为了可读性和为以后的扩展设置先例,我希望从 OnLayout 分支的函数看起来都相似。为此,我需要对它们进行划分并尽可能重用命名:

protected override void OnLayout(LayoutEventArgs levent)
    switch (LayoutShape)
    {
        case (square):
            doSquareLayout();
            break;
        case (round):
            doRoundLayout();
            break;
        etc..
        etc..
    }
void doSquareLayout()
{
    Region layerShape = (int Layer) =>
    {
        //do some calculation
        return new Region(Math.Ceiling(Math.Sqrt(ItemCount)));
    }
    int gradientAngle = (int itemIndex) =>
    {
        //do some calculation
        return ret;
    }
    //Common-ish layout code that uses layerShape and gradientAngle goes here
}
void doRoundLayout()
{
    Region layerShape = (int Layer) =>
    {
        //Do some calculation
        GraphicsPath shape = new GraphicsPath();
        shape.AddEllipse(0, 0, Width, Height);
        return new Region(shape);
    }
    int gradientAngle = (int itemIndex) =>
    {
        //do some calculation
        return ret;
    }
    //Common-ish layout code that uses layerShape and gradientAngle goes here
}

我现在找到的所有示例都说您必须声明一个委托,但我知道我已经看到了一个单行 lambda 声明...

【问题讨论】:

  • 没有等效于 C++ inline。如果您正在寻找单行函数定义,是的,这是可能的。 (见我的回答)

标签: c# lambda


【解决方案1】:

改用Func<int, int, int> areaOfRectangle = (int x, int y) => { return x * y;};

Func 担任代表

Look here for more info on lamda expression usage

This answer is also related and has some good info

如果您这样做是为了提高可读性并且要重现相同的函数layerShapegradientAngle,您可能希望为这些函数设置显式委托以显示它们实际上是相同的。只是一个想法。

【讨论】:

  • 顺便说一下,这和C++不一样inline
【解决方案2】:

这样试试;

Func<int, int, int> areaOfRectangle = (int x, int y) => { return x * y; };

检查 Func&lt;T1, T2, TResult&gt; 来自 MSDN

封装一个有两个参数并返回值的方法 TResult 参数指定的类型。

【讨论】:

    【解决方案3】:

    变量类型取决于你的参数和返回类型:

    Func<int,int,int> areaOfRectangle = (int x, int y) => {return x * y;};
    

    【讨论】:

      【解决方案4】:

      你已经接近了:

      Func<int, int, int> areaOfRectangle = (int x, int y) => {return x * y;};
      

      因此,对于您的具体情况,您的声明将是:

      Func<int, Region> layerShape = (int Layer) =>
      ...
      

      【讨论】:

        猜你喜欢
        • 2015-10-21
        • 2018-03-20
        • 1970-01-01
        • 1970-01-01
        • 2013-12-28
        • 2013-12-02
        • 1970-01-01
        • 1970-01-01
        • 2014-10-06
        相关资源
        最近更新 更多