C#反射编程之GetConstructor()方法解读
作者:木林森先生
C#中Type类的GetConstructor()方法用于获取指定类型的构造函数,该方法有多个重载版本,可以根据不同的参数获取不同特性的构造函数,返回值为ConstructorInfo类型,表示找到的构造函数,如果没有找到则返回null
C# GetConstructor()方法
Type类中的GetConstructor()方法,是用来获取当前 Type 所表示的类的特定构造函数。
有4个重载
| GetConstructor(BindingFlags, Binder, CallingConventions, Type[], ParameterModifier[]) |
| GetConstructor(BindingFlags, Binder, Type[], ParameterModifier[]) |
| GetConstructor(BindingFlags, Type[]) |
| GetConstructor(Type[]) |
以GetConstructor(Type[])为例
形参中的Type[],表示需要的构造函数的参数个数、顺序和类型的 Type 对象的数组。如果是空参构造函数,可以将Type[]设置为空数组。
返回类型是ConstructorInfo类型。表示某个公共实例构造函数的对象,如果没有,则为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);
}
}
}总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
