本文主要是介绍C#反射编程之GetConstructor()方法解读,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
《C#反射编程之GetConstructor()方法解读》C#中Type类的GetConstructor()方法用于获取指定类型的构造函数,该方法有多个重载版本,可以根据不同的参数获取不同特性的构造函...
C# GetConstructor()方法
Type类中的GetConstructor()方法,是用来获取当前 Type 所表示的类的特定构造函数。
有4个重载
| GetConstructor(BindingFlags, B编程inder, CallingConventions, Type[], ParameterModifier[]) |
| GetConstructor(BindingFlags, Binder, Type[], ParameterModifier[]) |
| GetConstructor(BindingFlags, Type[]) |
| GetConstructor(TyXRHeyQQnpe[]) |
以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
www.chinasem.cn {
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 =http://www.chinasem.cn myType.GetConstructor(types);
if (constructorInfoObj != null)
{
Console.WriteLine("The constructor of MyClass1 that takes an " +
"integer as a parameter is: ");
XRHeyQQn 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);
}
}
}总结
这篇关于C#反射编程之GetConstructor()方法解读的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!