开发者

Default arguments for structures

I have a function defined like this:

public static void ShowAbout(Point location, bool stripSystemAssemblies = false, bool r开发者_如何转开发eflectionOnly = false)

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.


You can do this:

public static void ShowAbout(Point location = new Point(), 
    bool stripSystemAssemblies = false,
    bool reflectionOnly = false)

From the C# 4 spec, section 10.6.1:

The expression in a default-argument must be one of the following:

  • a constant-expression
  • an expression of the form new S() where S is a value type
  • an expression of the form default(S) where S is a value type

So you could also use:

public static void ShowAbout(Point location = default(Point),
    bool stripSystemAssemblies = false,
    bool reflectionOnly = false)

EDIT: 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);
    ...
}

This would also let callers explicitly say, "you pick the default" by passing in null.


AFAICT CA1026 means you should replace it with functions that do not use default-arguments at all. So changing it as shown would still raise the violation.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜