2013-02-15 118 views
2

(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 
} 

所有我覺得現在說你要聲明一個代理,但我知道已經看到了一個襯墊的例子拉姆達聲明...

+0

沒有等同於C++'inline'。如果你正在尋找一個單線函數定義,是的,這是可能的。 (請參閱我的回答) – AppFzx 2013-05-14 13:14:51

回答

6

嘗試使用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,你可能希望有明確的委託這些功能表明它們實際上是相同的。只是一個想法。

+1

順便說一下,這與C++'inline'不一樣 – AppFzx 2013-05-14 13:13:32

1

變量類型是基於您的參數和返回值類型:

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

嘗試這樣;

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.

1

你接近:

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

因此,對於您的特定情況下,你的聲明將是:

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