[英]Why a value of type null cannot be used as a default parameter with type double?
Quick Question: 快速问题:
MSDN - Named and Optional Arguments (C# Programming Guide) states clearly that MSDN - 命名和可选参数(C#编程指南)明确指出
" Optional arguments enable you to omit arguments for some parameters. Both techniques can be used with methods, indexers, constructors , and delegates."
“ 可选参数使您可以省略某些参数的参数。这两种技术都可以与方法,索引器, 构造函数和委托一起使用。”
So instead of this: 所以不是这样的:
class MyClass
{
//..
public MyClass() { // Empty Constructor's Task }
public MyClass(SomeType Param1) { // 2nd Constructor's Task }
public MyClass(SomeType Param1, SomeType Param2) { // 3rd Constructor's Task }
}
I should be able to do this: 我应该能够做到这一点:
class MyClass
{
//..
public MyClass(SomeType Param1 = null, SomeType Param2 = null)
{
if (Param1)
{
if (Param2)
{
// 3rd constructor's Task
}
else
{
// 2nd constructor's Task
}
}
else
{
if (!Param2)
{
// Empty constructor's Task
}
}
}
}
Then why this is not working: 那为什么这不起作用:
public MyClass(double _x = null, double _y = null, double _z = null, Color _color = null)
{
// ..
}
Telling me: 告诉我:
A value of type "null" cannot be used as a default parameter because there are no standard conversions to type 'double'
“null”类型的值不能用作默认参数,因为没有标准转换来键入“double”
double
is a value type . double
是值类型 。 You'd need to wrap it in Nullable<T>
or ?
你需要将它包装在
Nullable<T>
或?
for shorthand, to indicate that it is nullable. 简而言之,表示它可以为空。
public MyClass(double? _x = null, double? _y = null, double? _z = null, Color _color = null)
{
// ..
}
As David explained in his answer, Double is not a nullable type. 正如大卫在他的回答中解释的那样,Double不是一个可以为空的类型。 In order to assign it a null value, you'll have to convert Double to
System.Nullable<double>
or double?
为了赋予它一个空值,你必须将Double转换为
System.Nullable<double>
或double?
The full answer will look something like: 完整的答案将如下所示:
public void MyMethod(double? param = null) { }
The obvious problem here is that instead of just passing it a double
value, you'll instead have to pass it a double?
这里显而易见的问题是,不是只传递一个
double
值,而是必须传递一个double?
value instead. 价值而不是。
I'm not sure of the exact scope of this functionality but you can always refer to defaults instead. 我不确定此功能的确切范围,但您总是可以参考默认值。 For instance:
例如:
public void MyMethod(double param = double.MinValue)
{
if (param == double.MinValue)
return;
}
Or something like that. 或类似的东西。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.