本聲明中'=>'是什麼意思?運算符'=>'在C#中的含義是什麼?
del = new SomeDelegate(() => SomeAction());
上述聲明與此相同嗎?
del = new SomeDelegate(this.SomeAction);
謝謝。
本聲明中'=>'是什麼意思?運算符'=>'在C#中的含義是什麼?
del = new SomeDelegate(() => SomeAction());
上述聲明與此相同嗎?
del = new SomeDelegate(this.SomeAction);
謝謝。
基本上它是指定一個匿名函數,它不需要調用SomeAction的參數。所以是的,它們在功能上是等同的。雖然不相等。使用拉姆達更等同於:
del = new SomeDelegate(this.CallSomeAction);
其中CallSomeAction被定義爲:
public void CallSomeAction()
{
this.SomeAction();
}
希望幫助!
他們做同樣的事情,但「()=> ...」語法是所謂的lambda表達式,因此是一樣的匿名函數。你完全可以忽略委託部分,只是讓編譯器爲你推斷委託類型。
del = this.SomeAction;
根據什麼類型「del」被seclared as。
編輯
使用lambda表達式或匿名方法或只是開始一個普通的方法使您能夠映射不具有委託的簽名委託方法。
例如,假設您有一個具有簽名bool myDelegate(int,int)的委託,但您希望使用簽名bool myMethod(string,string)處理該委託的方法。然後,您可以使用lambda表達式讓您使用像這樣的簡短語法進行內聯。
delegate bool myDelegate(int x, int y);
// With lambdas...
myDelegate del = (int a, int b) => myMethod(a.ToString(), b.ToString());
// With anonymous methods...
myDelegate del2 = delegate(int a, int b) { return myMethod(a.ToString(), b.ToString()); };
// The good ol' way without lambdas or anonymous methods...
myDelegate del3 = SomeDelegateHandler;
... then write a method somewhere else ...
// Handler method
private bool SomeDelegateHandler(int a, int b)
{
return myMethod(a.ToString(), b.ToString());
}
因此,大家可以看到lambda表達式和匿名方法基本上都是做處理委託的方法只是一個較短/直列方式。在你的情況下,你可能不需要額外的方法。這隻取決於委託簽名是否與您的方法簽名相同,對我而言,似乎是這樣。
=>
是Lambda Operator,lambda表達式就像是C#2.0 anonymous methods的演變。
您可以使用匿名方法和lambda表達式在一個非常類似的方法來創建委託實例:
Func<string,int> wordCount;
wordCount = delegate (string text) { return text.Split().Length; };
Console.WriteLine (wordCount("Hello World"));
使用lambda表達式:
Func<string,int> wordCount;
wordCount = (string text) => { text.Split().Length; };
Console.WriteLine (wordCount("Hello World"));
的 「=>」 可以改爲「去到「(source: Eric Lippert),並簡單地將參數從操作中的參數中分離出來。在這種情況下,lambda是過度殺傷力。更好的例子是:
var subList = list.FindAll(item => item.Type == "Foo");
(找到的所有項目,其中項目的類型是美孚)
等。在C#2.0,這也可以寫成:
var subList = list.FindAll(delegate(SomeType item) {
return item.Type == "Foo";});
而且是一個快速表達方式的功能「內聯」,同時也提供「關閉」支持 - 即它也可能是:
string itemType = ...
var subList = list.FindAll(item => item.Type == itemType);
做到這一點,否則就需要一個類型definiton在項目型傳:
class Searcher {
public string itemType;
public bool Find(SomeType item) {return item.Type == itemType;}
}
...
Searcher searcher = new Searcher();
searcher.itemType = ...
var subList = list.FindAll(searcher.Find);
其實,這是非常,很多編譯器不正是我們(無論是「委託」和lambda使用)。最大的區別是,lambda可以使用也可以使用表示Expression
,例如LINQ。
您應該對您的問題使用更具描述性的標題,例如「'=>'運算符在C#中的含義是什麼?」而不是「c#委託問題」 – 2009-02-22 03:52:53
謝謝,我會盡量更具描述性。 – Krakerjak 2009-02-22 03:53:41