委託及多播委託

c#中的委託類似於c  c++中的指針,委託就是概括了方法的簽名和返回值類型 ,委託可以理解爲定義的一個新的類。

所以在可以定義類的任何地方都可以定義委託,也可以在委託的定義上加訪問修飾符 public  private 等

1、定義一個委託  類似於方法的定義

該委託表示的方法有兩個long類型參數,返回值類型爲double

delegate double TwoLongOp (long first,long second);

定義一個不帶參數,返回一個string類型的值的委託

public delegate string GetString();

2、委託的簡單使用

 class Program
    {
        private delegate string GetAString();
        static void Main(string[] args)
        {
            int x=30;
            GetAString firstStringMetheod = new GetAString(x.ToString);
            Console.WriteLine("String is {0}", firstStringMetheod());

        }
    }

委託的實例化:

實例化一個GetAString類型的firstStringMethod變量

GetAString firtStringMethod = new GerAString(x.ToString);

也可以 GetAString firtStringMethod =x.ToString;

3、帶參委託和委託數組使用

 <pre name="code" class="csharp">class MathsOperations
    {
        public static double MultiplyByTwo(double value)
        {
            return value * 2;
        }
        public static double Square(double value)
        {
            return value * value;
        }
    }


 class Program
    {    
        delegate double DoubleOp(double x);
        static void Main(string[] args)
        {         
            DoubleOp[] operations =
            {
                MathsOperations.MultiplyByTwo,
                MathsOperations.Square
            };

            for (int i = 0; i < operations.Length; i++)
            {
                Console.WriteLine("using operations [{0}]", i);
                ProcessAndDisNum(operations[i], 2.0);
                ProcessAndDisNum(operations[i], 8);
                ProcessAndDisNum(operations[i], 16);
                Console.WriteLine();
            }

        }
       static void ProcessAndDisNum(DoubleOp action, double value)
        {
            double result = action(value);
            Console.WriteLine("Value is {0} ,result of operation is {1}", value, result);
        }
    }
泛型Action<T>委託表示可以引用一個void返回類型的方法,泛型Func<T>允許調用返回值的方法。最多可以傳遞16個參數類型和一個返回類型。Func<in T,out Result>表示一個帶參的方法

Func<double, double>[] operations=

{

MathOperations.MultiplyByTwo,

MathOperations.Squre

};

static void ProcessAndDisNum(<span style="font-size:18px;">Func<double, double> </span>action, double value)

4、多播委託的使用

如果調用多播委託就可以按順序連續調用多個方法,但是,多播委託的簽名必須返回void ,否則,只能得到委託調用的最後一個方法的結果

多播委託可以使用+= -= 運算符,用於在委託中添加或刪除方法調用

Action<double><pre name="code" class="html" style="font-size:18px;">operations 
= MathsOperations.MultiplyByTwo;operations += MathsOperations.Square;
ProcessAndDisNum(operations,2);
ProcessAndDisNum(operations,8);


使用多播委託時,如果其中一個方法拋出異常,整個迭代就會停止。

爲了避免這個問題可以自己迭代方法列表

Delegate[] delegates=operations .GetInvocationList();
foreach(Action d in delegates)
{

}





發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章