(Lambda 函数可能是也可能不是我要找的,我不确定)
基本上我要完成的是:
int areaOfRectangle = (int x, int y) => {return x * y;};
但它给出错误:“无法将 lambda 表达式转换为类型‘int’,因为它不是委托(delegate)类型”
更详细的问题(确实与问题无关,但我知道有人会问)是:
我有几个从覆盖的 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
}
我现在找到的所有例子都说你必须声明一个委托(delegate),但我知道我见过一个单行 lambda 声明...
最佳答案
尝试 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
如果您这样做是为了提高可读性并且要重现相同的功能 layerShape
和 gradientAngle
,您可能希望这些函数具有显式委托(delegate),以表明它们实际上是相同的。只是一个想法。
关于c# - 如何将变量定义为 lambda 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14902145/