This is a new Characteristic in C#3.0
namespace ConsoleUseExtensionMethod
{
public static class TestExtensionConsumer
{
public static void Main()
{
var s = "AlamInGamania";
// Extension Method
Console.WriteLine(s.WordCount());
Console.WriteLine("{0}{1}","效果同上",WordCount(s));
Console.ReadLine();
}
///summary
/// NonGenerics and must use static class
///summary
///<input> the input type is that want to extend </input>
///<return>the length of string</return>
public static int WordCount(this string v)
{
return v.Length; // Please "Note" Input parameter that The keyword "this".
}
}
}
If Type Built-in Functions has a same name with your func. name, C# 3.0 compiler will execute Built-in Function.
imagefish 發表在 痞客邦 留言(0) 人氣()
// Create a new dictionary of strings, with string keys.
Dictionary openWith =
new Dictionary();
// Add some elements to the dictionary. There are no
// duplicate keys, but some of the values are duplicates.
openWith.Add("txt", "notepad.exe");
openWith.Add("bmp", "paint.exe");
openWith.Add("dib", "paint.exe");
openWith.Add("rtf", "wordpad.exe");
// To get the TValue of rtf(TKey)
Console.WriteLine("For key = \"rtf\", value = {0}.",
openWith["rtf"];
// The indexer can be used to change the value associated
// with a key.
openWith["rtf"] = "Alamword.exe";
Console.WriteLine("For key = \"rtf\", value = {0}.",
openWith["rtf"]);
// The Add method throws an exception if the new key is
// already in the dictionary.
try
{
openWith.Add("txt", "winword.exe");
}
catch (ArgumentException)
{
Console.WriteLine("An element with Key = \"txt\" already exists.");
}
// If a key does not exist, setting the indexer for that key
// adds a new key/value pair.
// method(1) The indexer throws an exception if the requested key is
// not in the dictionary.
try
{
Console.WriteLine("For key = \"tif\", value = {0}.",
openWith["tif"]);
}
catch (KeyNotFoundException)
{
Console.WriteLine("Key = \"tif\" is not found.");
}
// method(2) When a program often has to try keys that turn out not to
// be in the dictionary, TryGetValue can be a more efficient
// way to retrieve values.
string value = "";
if (openWith.TryGetValue("tif", out value))
{
Console.WriteLine("For key = \"tif\", value = {0}.", value);
}
else
{
Console.WriteLine("Key = \"tif\" is not found.");
//Console.ReadLine();
}
參考資料:在Blog中放入程式碼
imagefish 發表在 痞客邦 留言(0) 人氣()