C#反射編程之GetConstructor()方法解讀
C# GetConstructor()方法
Type類中的GetConstructor()方法,是用來獲取當(dāng)前 Type 所表示的類的特定構(gòu)造函數(shù)。
有4個重載
GetConstructor(BindingFlags, Binder, CallingConventions, Type[], ParameterModifier[]) |
GetConstructor(BindingFlags, Binder, Type[], ParameterModifier[]) |
GetConstructor(BindingFlags, Type[]) |
GetConstructor(Type[]) |
以GetConstructor(Type[])為例
形參中的Type[],表示需要的構(gòu)造函數(shù)的參數(shù)個數(shù)、順序和類型的 Type 對象的數(shù)組。如果是空參構(gòu)造函數(shù),可以將Type[]設(shè)置為空數(shù)組。
返回類型是ConstructorInfo類型。表示某個公共實例構(gòu)造函數(shù)的對象,如果沒有,則為null。
實例代碼:
using System; using System.Reflection; public class MyClass1 { public MyClass1() { } public MyClass1(int i) { } public static void Main() { try { Type myType = typeof(MyClass1); Type[] types = new Type[1]; types[0] = typeof(int); // Get the constructor that takes an integer as a parameter. ConstructorInfo constructorInfoObj = myType.GetConstructor(types); if (constructorInfoObj != null) { Console.WriteLine("The constructor of MyClass1 that takes an " + "integer as a parameter is: "); Console.WriteLine(constructorInfoObj.ToString()); } else { Console.WriteLine("The constructor of MyClass1 that takes an integer " + "as a parameter is not available."); } } catch (Exception e) { Console.WriteLine("Exception caught."); Console.WriteLine("Source: " + e.Source); Console.WriteLine("Message: " + e.Message); } } }
總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
C#使用Fody實現(xiàn)監(jiān)控方法執(zhí)行時間
這篇文章主要為大家詳細(xì)介紹了C#如何使用Fody實現(xiàn)監(jiān)控方法執(zhí)行時間,文中的示例代碼講解詳細(xì),具有一定的學(xué)習(xí)價值,感興趣的小伙伴可以了解下2023-11-11C#動態(tài)生成DropDownList執(zhí)行失敗原因分析
這篇文章主要介紹了C#動態(tài)生成DropDownList執(zhí)行失敗原因分析,以一個實例形式分析了C#動態(tài)生成DropDownList的相關(guān)注意要點與使用技巧,具有一定參考借鑒價值,需要的朋友可以參考下2015-03-03C# Onnx CenterNet實現(xiàn)目標(biāo)檢測的示例詳解
這篇文章主要為大家詳細(xì)介紹了C# Onnx CenterNet實現(xiàn)目標(biāo)檢測的相關(guān)知識,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2023-12-12VsCode使用EmmyLua插件調(diào)試Unity工程Lua代碼的詳細(xì)步驟
這篇文章主要介紹了VsCode使用EmmyLua插件調(diào)試Unity工程Lua代碼,本文通過圖文并茂的形式給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-08-08