Determining if a parameter uses “params” using reflection in C#?

我是研究僧i 提交于 2019-12-04 02:52:55

问题


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?


回答1:


Check for the existence of [ParamArrayAttribute] on it.

The parameter with params will always be the last parameter.




回答2:


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

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



回答3:


A slightly shorter and more readable way:

static bool IsParams(ParameterInfo param)
{
    return param.IsDefined(typeof(ParamArrayAttribute), false);
}


来源:https://stackoverflow.com/questions/627656/determining-if-a-parameter-uses-params-using-reflection-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!