确定参数是否在C#中使用反射使用"params"?

Gab*_*erg 24 .net c# reflection params

考虑这个方法签名:

public static void WriteLine(string input, params object[] myObjects)
{
    // Do stuff.
}
Run Code Online (Sandbox Code Playgroud)

如何确定WriteLine方法的"myObjects"参数使用params关键字并且可以采用变量参数?

Meh*_*ari 35

检查[ParamArrayAttribute]它的存在.

参数with params将始终是最后一个参数.


CMS*_*CMS 18

检查ParameterInfo,如果ParamArrayAttribute已应用于它:

static bool IsParams(ParameterInfo param)
{
    return param.GetCustomAttributes(typeof (ParamArrayAttribute), false).Length > 0;
}
Run Code Online (Sandbox Code Playgroud)

  • 如果您只想检查自定义属性的存在,但不需要实际的属性实例,那么`IsDefined`比`GetCustomAttributes`更有效. (2认同)

Dej*_*jan 10

略微更短且更易读的方式:

static bool IsParams(ParameterInfo param)
{
    return param.IsDefined(typeof(ParamArrayAttribute), false);
}
Run Code Online (Sandbox Code Playgroud)