日期:2014-05-18  浏览次数:20804 次

反射时,实例化带参数的构造函数的类,报错
使用反射实例化一个带参数的构造函数的类,报错

//加载SayHello文档
Assembly asm = Assembly.Load("SayHello");

//获取类
Type type=asm.GetType("SayHello.Hello");

//从类中取得OutputNameAgeFavour()方法
MethodInfo OutPutNameAgeFavour_method = type.GetMethod("OutPutNameAgeFavour");

//实列化hello类,这里报错了,提示“没有找到Hello上的构造函数”
//说明:hello类只有一个带参数的构造函数,这里调用可能是按无参的调用,所以会有上面的报错,但是在这里怎么实例化一个带参数的构造函数的类
object obj = asm.CreateInstance("SayHello.Hello");
这个要怎么弄呀

------解决方案--------------------
用这个版本的方法,
Object Assembly.CreateInstance(
string typeName,
bool ignoreCase,
BindingFlags bindingAttr,
Binder binder,
Object[] args,
CultureInfo culture,
Object[] activationAttributes
)

args就是参数,可以传入new object[]{xxx},xxx是你要传入的构造函数参数,

其他参数用缺省的,慢慢凑,