C# 委托(delegate) 的小例子
更新時間:2013年03月08日 15:11:37 作者:
利用委托(delegate)好像也能解決避免大量switch case的代碼。
代碼如下:
復(fù)制代碼 代碼如下:
static void Main(string[] args)
{
Console.WriteLine(Exec(GetSet));
Console.ReadKey();
}
//定義委托,用于將方法做為參數(shù)傳給Exec.
public delegate string GetResultDelegate();
public static string Get()
{
return "get";
}
public static string GetTest()
{
return "gettest";
}
public static string GetSet()
{
return "getSet";
}
public static string Exec(GetResultDelegate getResult)
{
return getResult();
}
利用委托,可以把一個方法做為另一個方法的參數(shù),直接執(zhí)行參數(shù)就OK了。和javascript的函數(shù)有點相似,javascript里面的函數(shù)也可以做為另一個函數(shù)的參數(shù)。javascript中直接可以用函數(shù)名做參數(shù),而c#中必須通過委托,轉(zhuǎn)個彎,實現(xiàn)同樣的功能!
相關(guān)文章
C#中派生類調(diào)用基類構(gòu)造函數(shù)用法分析
這篇文章主要介紹了C#中派生類調(diào)用基類構(gòu)造函數(shù)用法,實例分析了派生類調(diào)用基類構(gòu)造函數(shù)的技巧,具有一定參考借鑒價值,需要的朋友可以參考下2015-04-04

