结构的默认参数 [英] Default arguments for structures
问题描述
我有一个这样定义的函数:
I have a function defined like this:
public static void ShowAbout(Point location,bool stripSystemAssemblies = false,bool reflectionOnly = false)
此标志CA1026将方法ShowAbout'替换为提供所有默认参数的重载。我不能做点位置=新点(0,0)
或点位置= Point.Empty
是编译时常量,因此不能是该函数参数的默认值。所以问题是,如何指定结构的默认参数值?
This flags CA1026 "Replace method 'ShowAbout' with an overload that supplies all default arguments". I can't do Point location = new Point(0, 0)
or Point location = Point.Empty
because neither are compile time constants and therefore cannot be the default values for that function argument. So the question is, how does one go about specifying default argument values for structures? If it can't be done, likely I'll go for suppressing CA1026 in source with whatever justification someone here gives.
推荐答案
如果无法做到这一点,我可能会使用任何理由来抑制CA1026。您可以这样做:
You can do this:
public static void ShowAbout(Point location = new Point(),
bool stripSystemAssemblies = false,
bool reflectionOnly = false)
从C#4规范第10.6.1节:
From the C# 4 spec, section 10.6.1:
默认参数
中的表达式必须为以下之一:
The expression in a default-argument must be one of the following:
- a 常量表达式
- c> new S()其中
S
是值类型 - c $ c> default(S)其中
S
是值类型
- a constant-expression
- an expression of the form
new S()
whereS
is a value type - an expression of the form
default(S)
whereS
is a value type
因此,您也可以使用:
public static void ShowAbout(Point location = default(Point),
bool stripSystemAssemblies = false,
bool reflectionOnly = false)
EDIT:如果你想默认一个值其他比点(0,0),值得了解另一个诀窍:
If you wanted to default to a value other than the point (0, 0), it's worth knowing about another trick:
public static void ShowAbout(Point? location = null
bool stripSystemAssemblies = false,
bool reflectionOnly = false)
{
// Default to point (1, 1) instead.
Point realLocation = location ?? new Point(1, 1);
...
}
这也会让呼叫者明确地说:你选择默认通过传入null。
This would also let callers explicitly say, "you pick the default" by passing in null.
这篇关于结构的默认参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!