微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

原文地址:https://www.jb51.cc/csharp/93309.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐