可选参数由[可选] C#,检查args传递

时间:2016-03-19 00:24:08

标签: c#

我有这样的类构造函数:

public Script(string scriptName, [Optional] ICollection<Tuple<string, bool>> internalFunctions, [Optional] long randomIdentifier) { }

那么,如何检查,是否在randomIdentifier或internalFunctions中传递了什么? 那么,是

new Script("test1")

new Script("test1", null)

new Script("test1", null, 1)

称为?

谢谢。

1 个答案:

答案 0 :(得分:1)

如果没有显式传递值,那么这些参数将具有默认值,您必须自己测试这些值:

public Script(string scriptName, [Optional] ICollection<Tuple<string, bool>> internalFunctions, [Optional] long randomIdentifier)
{
    if (internalFunctions != null)
    {
        // do something that needs internalFunctions to have a value
    }

    if (randomIdentifier != 0)
    {
        // do something that needs randomIdentifier to have a valid value
    }
    else
    {
        // either a value wasn't passed, or the value 0 was passed...
        //   you can't be sure, so you might want to make this nullable
    }
}