最近Orcas Beta1剛出,C#3.0炒得越來越熱,一些新特性也是相當誘人,這幾天,把.net3.0的環境終於是搭上了, 配環境的經驗以後再說,這裏先談一下,C#3.0裏的一個新特性,Extension Methods擴展方法,個人理解,有點仿JavaScript裏的Prototype,主要是不用重編譯,就可對一個類型加入方法,引用類型和值類型都是可以的.
擴展方法允許開發人員往一個現有的CLR類型的公開契約(contract)中添加新的方法,而不用生成子類或者重新編譯原來的類型。擴展方法有助於把今天動態語言中流行的對duck typing的支持之靈活性,與強類型語言之性能和編譯時驗證融合起來。
擴展方法促成了好多有用的使用場景,並使在作爲Orcas一部分發布的.NET版本中引進的非常強大的LINQ查詢框架成爲可能。
下面是一個簡單的示例:
public static class test
{
public static bool fun(this string s)
{
return s.Length>10&&s.Contains("test");
}
public static double cal(this int a)
{
return a*3.14159*a;
}
public static bool In(this object o,IEnumerable c)
{
foreach(object obj in c)
if(obj.Equals(o))
return true;
return false;
}
}
{
public static bool fun(this string s)
{
return s.Length>10&&s.Contains("test");
}
public static double cal(this int a)
{
return a*3.14159*a;
}
public static bool In(this object o,IEnumerable c)
{
foreach(object obj in c)
if(obj.Equals(o))
return true;
return false;
}
}
class必須是static,every method也必須是public static,其中的this是指要把方法加入的類型,如string就是添加到string類型中,前面兩個方法隨便做個測試,沒什麼意義的,第三個方法,是遍歷一個集合,判斷是否包含o.
下面是Main代碼塊:
class Program
{
static void Main(string[] args)
{
string s="first test";
Console.WriteLine(s.fun());
int a=42324;
Console.WriteLine(a.cal());
string[] str={"abcd","efgh","hijk","dog","cat","fire","lay"};
Console.WriteLine("dog".In(str));
}
}
{
static void Main(string[] args)
{
string s="first test";
Console.WriteLine(s.fun());
int a=42324;
Console.WriteLine(a.cal());
string[] str={"abcd","efgh","hijk","dog","cat","fire","lay"};
Console.WriteLine("dog".In(str));
}
}