C#中Invoke的具體使用
在 C# 中,Invoke() 是一個用于調(diào)用方法的方法,它能夠在運(yùn)行時動態(tài)地調(diào)用一個方法。
Invoke() 方法的使用方式有兩種:
通過 MethodInfo 對象調(diào)用:
using System.Reflection; namespace ConsoleApp_Invoke { ? ? public class Program ? ? { ? ? ? ? static void Main(string[] args) ? ? ? ? { ? ? ? ? ? ? MethodInfo openMethodInfo = typeof(MyStore).GetMethod("Open"); ? ? ? ? ? ? openMethodInfo.Invoke(new MyStore(), null); ?// 如果調(diào)用的方法參數(shù)為空,則第二個參數(shù)為null ? ? ? ? ? ? MethodInfo sellMethodInfo = typeof(MyStore).GetMethod("Sell"); ? ? ? ? ? ? sellMethodInfo.Invoke(new MyStore(), new object[] { "蘋果", 10 }); ?// 如果調(diào)用的方法有參數(shù),則第二個參數(shù)傳遞一個參數(shù)數(shù)組 ? ? ? ? } ? ? } ? ? public class MyStore ? ? { ? ? ? ? public void Open() ? ? ? ? { ? ? ? ? ? ? Console.WriteLine("早上商店進(jìn)行開張了"); ? ? ? ? } ? ? ? ? public void Sell(string Name, int count) ? ? ? ? { ? ? ? ? ? ? Console.WriteLine($"出售{count}件{Name}"); ? ? ? ? } ? ? } }
在上面的示例中,我們首先通過 typeof(MyStore).GetMethod("MyMethod") 獲取了 Open 方法的 MethodInfo 對象,然后使用 Invoke() 方法調(diào)用該方法。
Invoke() 方法接受兩個參數(shù):
- 第一個參數(shù)是要調(diào)用方法的對象實(shí)例,如果方法是靜態(tài)的,則可以傳遞 null;
- 第二個參數(shù)是方法的參數(shù)數(shù)組,如上面我們調(diào)用Sell方法。
通過委托調(diào)用:
Action<string> myDelegate = new MyClass().MyMethod; // 創(chuàng)建委托對象 myDelegate.Invoke("Hello"); // 調(diào)用委托
在上面的示例中,我們首先創(chuàng)建了一個 Action<string> 委托對象,并將其初始化為 MyMethod 方法,然后使用 Invoke() 方法調(diào)用委托。與第一種方式相比,這種方式更加簡潔,但使用委托調(diào)用方法需要確保委托的簽名與要調(diào)用的方法的簽名匹配。
無論使用哪種方式,Invoke() 方法都可以用于調(diào)用方法并傳遞參數(shù)。
需要注意的是,Invoke() 方法的調(diào)用可能會引發(fā) TargetException、MethodAccessException、TargetInvocationException 等異常,所以在實(shí)際使用中應(yīng)該進(jìn)行異常處理。
到此這篇關(guān)于C#中Invoke的具體使用的文章就介紹到這了,更多相關(guān)C# Invoke內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
C#中Sleep() 和 Wait()的區(qū)別小結(jié)
Sleep()和 Wait()是兩個不同的方法,用于控制線程的執(zhí)行,本文主要介紹了C#中Sleep()和Wait()的區(qū)別小結(jié),具有一定的參考價(jià)值,感興趣的可以了解一下2024-04-04C# SendInput 模擬鼠標(biāo)操作的實(shí)現(xiàn)方法
C# SendInput 模擬鼠標(biāo)操作的實(shí)現(xiàn)方法,需要的朋友可以參考一下2013-04-04unity通過Mesh網(wǎng)格繪制圖形(三角形、正方體、圓柱)
這篇文章主要為大家詳細(xì)介紹了unity通過Mesh網(wǎng)格繪制圖形:三角形、正方體、圓柱,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-11-11