如何定义变量lambda函数
(lambda函数可能会或可能不是我要找的,我不知道)如何定义变量lambda函数
基本上我想要实现的是:
int areaOfRectangle = (int x, int y) => {return x * y;};
,但它给错误:“无法转换lambda表达式类型‘诠释’,因为它不是一个委托类型”
更详细的问题(即真有无关的问题,但我知道有人会问)是:
我有几个函数从重写的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
}
所有我觉得现在说你要声明一个代理,但我知道我已经看到了一个衬垫的例子拉姆达声明...
尝试使用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
,你可能希望有明确的委托这些功能表明它们实际上是相同的。只是一个想法。
顺便说一下,这与C++'inline'不一样 – AppFzx 2013-05-14 13:13:32
变量类型是基于您的参数和返回值类型:
Func<int,int,int> areaOfRectangle = (int x, int y) => {return x * y;};
尝试这样;
Func<int, int, int> areaOfRectangle = (int x, int y) => { return x * y; };
检查从MSDNFunc<T1, T2, TResult>
;
Encapsulates a method that has two parameters and returns a value of the type specified by the TResult parameter.
你接近:
Func<int, int, int> areaOfRectangle = (int x, int y) => {return x * y;};
因此,对于您的特定情况下,你的声明将是:
Func<int, Region> layerShape = (int Layer) =>
...
没有等同于C++'inline'。如果你正在寻找一个单线函数定义,是的,这是可能的。 (请参阅我的回答) – AppFzx 2013-05-14 13:14:51