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