c# – 结构的默认参数

我有一个这样定义的函数

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

这标志着CA1026“替换方法”ShowAbout’与提供所有认参数的重载“.我不能做点位置=新点(0,0)或点位置= Point.Empty,因为既不是编译时常量,因此不能是该函数参数的认值.所以问题是,关于如何指定结构的认参数值呢?如果不能完成,可能我会以源头上的任何理由来禁止CA1026.

解决方法

你可以这样做:
public static void ShowAbout(Point location = new Point(),bool reflectionOnly = false)

从C#4规范,第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

所以你也可以使用:

public static void ShowAbout(Point location = default(Point),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”来选择认值.

相关文章

在要实现单例模式的类当中添加如下代码:实例化的时候:frmC...
1、如果制作圆角窗体,窗体先继承DOTNETBAR的:public parti...
根据网上资料,自己很粗略的实现了一个winform搜索提示,但是...
近期在做DSOFramer这个控件,打算自己弄一个自定义控件来封装...
今天玩了一把WMI,查询了一下电脑的硬件信息,感觉很多代码都...
最近在研究WinWordControl这个控件,因为上级要求在系统里,...