请教高手,在利用反射时,如何来识别某个参数是个 params 的问题。
例如:
public class cls2{
public void fnc1(object objArg, params string[] strParams){}
public void fnc2(object objArg, string[] strNomaul){}
} MothodeFnc1.Invoke(cls2, new object[]{ arg1, new string[]{...}}); MothodeFnc2.Invoke(cls2, new object[]{ arg1, new string[]{...}}); 在这里我想请教的是在调用Invoke之前如何知道fnc1的第2个参数是params的?
例如:
public class cls2{
public void fnc1(object objArg, params string[] strParams){}
public void fnc2(object objArg, string[] strNomaul){}
} MothodeFnc1.Invoke(cls2, new object[]{ arg1, new string[]{...}}); MothodeFnc2.Invoke(cls2, new object[]{ arg1, new string[]{...}}); 在这里我想请教的是在调用Invoke之前如何知道fnc1的第2个参数是params的?
在上面的代码中,参数的列表中你已经声明params类型参数啦。
params 构造函数声明数组 而不知道数组长度 用的
在方法声明中的 params 关键字之后不允许任何其他参数
他接的是数组,并且在方法声明中只允许一个 params 关键字。
这个我知道,但是
在这里我想请教的是在调用Invoke之前如何知道fnc1的第2个参数是params的?
也就是说,在
MothodeFnc1.Invoke(cls2, new object[]{ arg1, new string[]{...}});
之前,实际的fnc1的第二个参数 strParams它是不是可省略的我现在能否知道。
public void Test(string[] args)
{
bool result = HasParams(typeof(cls2).GetMethod("fnc1"));
} public static bool HasParams(MethodInfo mi)
{
ParameterInfo[] pis = mi.GetParameters();
if (pis.Length > 0)
{
foreach (Attribute attribute in pis[pis.Length - 1].GetCustomAttributes(false))
{
if (attribute is ParamArrayAttribute) //<---
{
return true;
}
}
}
return false;
}
检查可以用ParamArrayAttribute不过反射调用的时候没有区别 - 下面的红字部分不能省略(当然和string[]一样,也可以传入null)。
MothodeFnc1.Invoke(cls2, new object[]{ arg1, new string[]{...}});
首先谢谢你的回答。
您所说的方法是对于具有自己定义了CustomAttributes时候是有效的,
通常类型的参数之前没有给它特别加Attribute的话,pis[x].Attributes的
返回值则是Nono。
而且pis[x].Attributes也不能和ParamArrayAttribute进行相对的操作。
1、试运行3楼的代码,一个试验用不来几分钟的。
2、看3楼提供的ParamArrayAttribute链接,理解ParamArrayAttribute是做什么的。
我在5楼答复的时候,用了自己的代码测试,
那个代码有问题,当时没有发现,走了弯路了,不好意思。再次表示感谢!另外,我还想有一个问题请教。
如何知道某个类的 Instance 已经实际存在了。
这个我会另外发一个帖子的。