程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> 關於C語言 >> c#3.0系列:Extension Method(3)

c#3.0系列:Extension Method(3)

編輯:關於C語言

擴展接口類型

看下面的例子


1public static void fnIntExtensionMethod()
2    {
3
4      Console.WriteLine("***** Extending an interface *****\n");
5      // Call IMath members from MyCalc object.
6      MyCalc c = new MyCalc();
7      Console.WriteLine("1 + 2 = {0}", c.Add(1, 2));
8      Console.WriteLine("1 - 2 = {0}", c.Subtract(1, 2));
9      // Can also cast into IBasicMath to invoke extension.
10      Console.WriteLine("30 - 9 = {0}", ((IMath)c).Subtract (30, 9));
11      // This would NOT work!
12       //IMath itfBM = new IMath();
13       //itfBM.Subtract(10, 10);
14      Console.ReadLine();
15
16    }
17
18public static class MyExtensionMethods
19  {
20    // this代表擴展方法應用於string類型上
21    // ToInt32()是將string類型轉換為int類型的擴展方法
22    public static int ToInt32(this string s)
23    {
24      int i;
25      Int32.TryParse(s, out i);
26      return i;
27    }
28
29    public static int Subtract(this IMath itf ,int x, int y)
30    {
31      return x - y;
32    }
33
34  }
35public interface IMath
36  {
37    int Add(int x, int y);
38  }
39
40class MyCalc : IMath
41  {
42    public int Add(int x, int y)
43    {
44      return x + y;
45    }
46  }

注意這裡擴展時必須給出函數的實現,擴展接口後,顯然不能直接在接口上調 用這些擴展函數,只能理解為,所有繼承該接口的對象新增加了這些擴展函數功 能。

注意事項:

引用擴展函數

必須引用定義擴展函數的命名空間,否則擴展函數不可用。

智能提示

Visual studio 的智能提示將擴展函數標記為向下的藍色箭頭。

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved