Determining if a parameter uses “params” using ref

2020-04-01 08:52发布

Consider this method signature:

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

How can I determine that the WriteLine method's "myObjects" pararameter uses the params keyword and can take variable arguments?

3条回答
▲ chillily
2楼-- · 2020-04-01 09:04

A slightly shorter and more readable way:

static bool IsParams(ParameterInfo param)
{
    return param.IsDefined(typeof(ParamArrayAttribute), false);
}
查看更多
可以哭但决不认输i
3楼-- · 2020-04-01 09:07

Check the ParameterInfo, if ParamArrayAttribute has been applied to it:

static bool IsParams(ParameterInfo param)
{
    return param.GetCustomAttributes(typeof (ParamArrayAttribute), false).Length > 0;
}
查看更多
We Are One
4楼-- · 2020-04-01 09:18

Check for the existence of [ParamArrayAttribute] on it.

The parameter with params will always be the last parameter.

查看更多
登录 后发表回答