日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無(wú)先后,達(dá)者為師

網(wǎng)站首頁(yè) 編程語(yǔ)言 正文

C#委托方法Func()中GetInvocationList()方法的用法介紹_基礎(chǔ)應(yīng)用

作者:癡者工良 ? 更新時(shí)間: 2022-03-28 編程語(yǔ)言

在日常使用委托時(shí),有以下常用方法

方法名稱(chēng) 說(shuō)明
?Clone ? 創(chuàng)建委托的淺表副本。
?GetInvocationList ? 按照調(diào)用順序返回此多路廣播委托的調(diào)用列表。
?GetMethodImpl ??返回由當(dāng)前的 MulticastDelegate 表示的靜態(tài)方法。
?GetObjectData ? 用序列化該實(shí)例所需的所有數(shù)據(jù)填充?SerializationInfo?對(duì)象。
?MemberwiseClone ? 創(chuàng)建當(dāng)前?Object?的淺表副本。
?RemoveImpl ? 調(diào)用列表中移除與指定委托相等的元素

GetInvocationList() 的用途

當(dāng)委托有多個(gè)返回值時(shí)

當(dāng)你編寫(xiě)一個(gè) delegate委托 或 Func<>泛型委托 ,并為實(shí)例綁定多個(gè)方法時(shí),每個(gè)方法都有一個(gè)返回值??赡軙?huì)遇到這種情況:

class Program
    {
        public static string a(string str)
        {
            Console.WriteLine("方法a");
            return str+"方法a";
        }
        public static string b(string str)
        {
            Console.WriteLine("方法b");
            return str + "方法b";
        }
        public static string c(string str)
        {
            Console.WriteLine("方法c");
            return str + "方法c";
        }
        static void Main(string[] args)
        {
            Func<string, string> func=a;
            func += b;
            func += c;
            Console.WriteLine(func("測(cè)試"));
            Console.ReadKey();
        }

    }

調(diào)用委托后,只能獲取到最后一個(gè)調(diào)用方法的返回值。

使用 GetInvocationList()

GetInvocationList() 能夠返回 這個(gè)委托的方法鏈表。

通過(guò)使用循環(huán),把每個(gè)方法順序調(diào)用一次,每次循環(huán)中都會(huì)產(chǎn)生當(dāng)前調(diào)用方法的返回值。

class Program
{
    public static string a(string str)
    {
        Console.WriteLine("方法a");
        return str+"方法a";
    }
    public static string b(string str)
    {
        Console.WriteLine("方法b");
        return str + "方法b";
    }
    public static string c(string str)
    {
        Console.WriteLine("方法c");
        return str + "方法c";
    }
    static void Main(string[] args)
    {
        Func<string, string> func=a;
        func += b;
        func += c;
        var funclist = func.GetInvocationList();
        foreach (Func<string, string> f in funclist)
        {
            Console.WriteLine(f("測(cè)試"));
        }
        Console.ReadKey();
    }

相當(dāng)于把委托里順序調(diào)用的方法分離成一個(gè)列表,通過(guò)循環(huán)調(diào)用,循環(huán)獲取。

原文鏈接:https://www.cnblogs.com/whuanle/p/10035549.html

欄目分類(lèi)
最近更新