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);
}
}
}总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
发表评论