检查方法里面一些可选的参数是否传递 [英] Check inside method whether some optional argument was passed
问题描述
我如何检查是否可选参数传递给方法?
公共无效ExampleMethod(INT要求,串optionalstr =默认字符串,
INT optionalint = 10)
{
如果(optionalint传递)
的回报;
}
另一种方法是使用可空< T&取代。的HasValue
( MSDN定义的, MSDN范例):
INT default_optionalint = 0;
公共无效ExampleMethod(INT要求,诠释?optionalint,
串optionalstr =默认字符串)
{
INT _optionalint = optionalint? default_optionalint;
}
好了,争论总是传递。默认参数值只是确保用户不具有的明确的调用函数时指定它们。
当编译器看到的调用是这样的:
ExampleMethod( 1);
它静静地将其转换为:
ExampleMethod(1,默认字符串,10);
所以它不是techically可能确定论点是在运行时通过。你可以得到的最接近的是:
如果(optionalstr ==默认字符串)
的回报;
但这样做的行为相同,如果用户把它称为明确如下:
ExampleMethod(1,默认字符串);
另一种方法,如果你真的想这取决于是否提供一个参数有不同的行为,是摆脱默认参数和使用重载代替,像这样的:
公共无效ExampleMethod(INT必需)
{
// optionalstr并没有提供optionalint
}
公共无效ExampleMethod(INT要求,串optionalstr)
{
// optionalint没有提供
}
公共无效ExampleMethod(INT要求,串optionalstr,诠释optionalint)
{
//提供的所有参数
}
How do I check if an optional argument was passed to a method?
public void ExampleMethod(int required, string optionalstr = "default string",
int optionalint = 10)
{
if (optionalint was passed)
return;
}
Another approach is to use Nullable<T>.HasValue
(MSDN definitions, MSDN examples):
int default_optionalint = 0;
public void ExampleMethod(int required, int? optionalint,
string optionalstr = "default string")
{
int _optionalint = optionalint ?? default_optionalint;
}
Well, arguments are always passed. Default parameter values just ensure that the user doesn't have to explicitly specify them when calling the function.
When the compiler sees a call like this:
ExampleMethod(1);
It silently converts it to:
ExampleMethod(1, "default string", 10);
So it's not techically possible to determine if the argument was passed at run-time. The closest you could get is:
if (optionalstr == "default string")
return;
But this would behave identically if the user called it explicitly like this:
ExampleMethod(1, "default string");
The alternative, if you really want to have different behavior depending on whether or not a parameter is provided, is to get rid of the default parameters and use overloads instead, like this:
public void ExampleMethod(int required)
{
// optionalstr and optionalint not provided
}
public void ExampleMethod(int required, string optionalstr)
{
// optionalint not provided
}
public void ExampleMethod(int required, string optionalstr, int optionalint)
{
// all parameters provided
}
这篇关于检查方法里面一些可选的参数是否传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!