加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 结构的默认参数

发布时间:2020-12-15 03:56:13 所属栏目:百科 来源:网络整理
导读:我有一个这样定义的函数: public static void ShowAbout(Point location,bool stripSystemAssemblies = false,bool reflectionOnly = false) 这标志着CA1026“替换方法”ShowAbout’与提供所有默认参数的重载“.我不能做点位置=新点(0,0)或点位置= Point.Em
我有一个这样定义的函数:

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”来选择默认值.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读