C#可选数组参数

栏目: ASP.NET · 发布时间: 7年前

内容简介:http://stackoverflow.com/questions/39971222/c-sharp-optional-array-parameter-for-class本站文章除注明转载外,均为本站原创或编译转载请明显位置注明出处:C#可选数组参数

我知道这可以使用null,所以我有一个解决方法,但我想知道是否有一个更好的方法,我可以有一个可选的int []参数的类?

class PriceLevels
{
    public int[] priceLevels { get; }
    private readonly int[] defaultPriceLevels = { 2, 3, 3, 4, 5, 6 };

    public PriceLevels(int[] newPriceLevels = defaultPriceLevels)
    {
        priceLevels = newPriceLevels;
    }
}

这给我一个错误,表示它是一个无效的表达式defaultPriceLevels必须是常量.如何解决这个问题?

我可以做的一件事情就是这样,但我并不喜欢这个解决方案

class PriceLevels
{
    public int[] priceLevels { get; }
    private readonly int[] defaultPriceLevels = { 2, 3, 3, 4, 5, 6 };

    public PriceLevels(int[] newPriceLevels = null)
    {
        if(newPriceLevels == null) 
            priceLevels = defaultPriceLevels;
        else 
            priceLevels = newPriceLevels;
    }
}

一个更好的设计在一起将是有2个构造函数获得一个int []而另一个不是:

class PriceLevels
{
    public int[] priceLevels { get; set; }
    private readonly int[] defaultPriceLevels = { 2, 3, 3, 4, 5, 6 };

    public PriceLevels()
    {
        priceLevels = defaultPriceLevels;
    }

    public PriceLevels(int[] newPriceLevels)
    {
       priceLevels = newPriceLevels;
    }
}

如果没有,不知道我是否会称之为“更好”,但您可以使用params关键字:

class PriceLevels
{
    public int[] priceLevels { get; set; }
    private readonly int[] defaultPriceLevels = { 2, 3, 3, 4, 5, 6 };

    public PriceLevels(params int[] newPriceLevels)
    {
        priceLevels = newPriceLevels.Length == 0 ? defaultPriceLevels : newPriceLevels;
    }
}

另外,根据设计,我不相信PriceLevels有责任决定默认值是什么,也许应该在任何情况下将其作为依赖关系 – 请参见 SOLIDDependency Injection .那么你只能有一个构造函数:

class PriceLevels
{
    public int[] priceLevels { get; set; }

    public PriceLevels(int[] newPriceLevels)
    {
       priceLevels = newPriceLevels;
    }
}

http://stackoverflow.com/questions/39971222/c-sharp-optional-array-parameter-for-class

本站文章除注明转载外,均为本站原创或编译

转载请明显位置注明出处:C#可选数组参数


以上所述就是小编给大家介绍的《C#可选数组参数》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

How to Design Programs, 2nd Edition

How to Design Programs, 2nd Edition

Matthias Felleisen、Robert Bruce Findler、Matthew Flatt、Shriram Krishnamurthi / MIT Press / 2018-5-4 / USD 57.00

A completely revised edition, offering new design recipes for interactive programs and support for images as plain values, testing, event-driven programming, and even distributed programming. This ......一起来看看 《How to Design Programs, 2nd Edition》 这本书的介绍吧!

CSS 压缩/解压工具
CSS 压缩/解压工具

在线压缩/解压 CSS 代码

RGB转16进制工具
RGB转16进制工具

RGB HEX 互转工具

Base64 编码/解码
Base64 编码/解码

Base64 编码/解码