C# 委托和接口


能用委托解決的事情,接口也都可以解決。如下所示:

 

   public static void Main() { int[] values = { 1, 2, 3, 4 }; Util.TransformAll(values, new Squarer()); foreach (int i in values) { Console.WriteLine(i); //輸出1,4,9,16
 } }            public interface ITransformer { int Transform(int x); } public class Util { public static void TransformAll(int[] values, ITransformer t) { for (int i = 0; i < values.Length; i++) { values[i] = t.Transform(values[i]); } } } class Squarer : ITransformer { public int Transform(int x) { return x * x; } }  

上面的例子中沒有多播,且接口中只定義了一個方法。如果訂閱者需要支持不同的轉換方式(如平方、立方),則需要多次實現ITransformer接口。

這個時候你就會發現很煩,因為每種轉換都要寫一個實現類!如下所示:

        public static void Main() { int[] datas = { 1, 2, 3, 4 }; Util.TransformAll(datas, new Cuber()); foreach (int i in datas) { Console.WriteLine(i); //輸出1,8,27,64
 } } ...     class Squarer : ITransformer { public int Transform(int x) { return x * x; } } class Cuber : ITransformer { public int Transform(int x) { return x * x * x; } }

 

什么時候委托優於接口呢?

1、接口內只定義一個方法

2、需要進行多播

3、需要多次實現接口

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM