结构的默认参数

我有一个像这样定义的函数:

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

这标志CA1026“替换方法’ShowAbout’与提供所有默认参数的重载”。 我不能做Point location = new Point(0, 0)Point location = Point.Empty因为它们都不是编译时常量,因此不能是该函数参数的默认值。 所以问题是,如何为结构指定默认参数值? 如果无法完成,我可能会在这里用任何理由来压制CA1026。

你可以这样做:

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

从C#4规范,第10.6.1节:

default-argument中的表达式必须是以下之一:

  • 一个常数表达式
  • forms为new S()的表达式,其中S是值类型
  • forms为default(S)的表达式,其中S是值类型

所以你也可以使用:

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

编辑:如果你想默认值不是点(0,0),那么值得了解另一个技巧:

 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明确地说“你选择默认值”。

AFAICT CA1026意味着您应该将它替换为完全不使用默认参数的函数。 因此,如图所示更改它仍然会引发违规行为。