问题描述
(lambda函数可能会或可能不会有什么我要找的,我不知道)
(Lambda function may or may not be what I'm looking for, I'm not sure)
从本质上讲就是我要完成的是这样的:
Essentially what I'm trying to accomplish is this:
int areaOfRectangle = (int x, int y) => {return x * y;};
但它给了错误:无法将lambda表达式类型'诠释',因为它不是委托键入
but it gives error: "Cannot convert lambda expression to type 'int' because it is not a delegate type"
更详细的问题(这真的无关的问题,但我知道有人会问)是:
The more detailed problem (that really has nothing to do with the question, but I know someone will ask) is:
我有几个功能,从一个覆盖OnLayout和一些更多的功能,每个那些依赖于分支。为了提高可读性,并设置为以后的扩展先例,我想要的功能分支从OnLayout所有类似于。要做到这一点,我需要划分它们和重用命名尽可能的:
I have several functions that branch from an overridden OnLayout and several more functions that each of those depend on. For readability and to set precedent for later expansion, I want the functions that branch from OnLayout to all look similar. To do that, I need to compartmentalize them and reuse naming as much as possible:
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
}
所有我现在找到的例子说,你必须声明一个委托,但我的知道的我见过一个班轮拉姆达声明...
All the examples I find right now say you have to declare a delegate but I know I've seen a one liner lambda declaration...
推荐答案
尝试 Func键< INT,INT,INT> areaOfRectangle =(INT X,int y)对= GT; {返回X * Y;};
而不是
函数功能
的工作原理为代表
的
的
如果你正在做它的可读性和将要再现相同功能 layerShape
和 gradientAngle
,您可能希望为这些功能明确的代表,以表明他们其实都是一样的。仅仅是一个想法。
If you're doing it for readability and are going to reproduce the same functions layerShape
and gradientAngle
, you might want to have explicit delegates for those functions to show they are in fact the same. Just a thought.
这篇关于如何定义变量lambda函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!