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#可选数组参数》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

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

Windows内核原理与实现

Windows内核原理与实现

潘爱民 / 电子工业出版社 / 2010年4月 / 99.00元

本书从操作系统原理的角度,详细解析了Windows如何实现现代操作系统的各个关键部件,包括进程、线程、物理内存和虚拟内存的管理,Windows中的同步和并发性支持,以及Windows的I/O模型。在介绍这些关键部件时,本书直接以Windows的源代码(WRK, Windows Research Kernel)为参照,因而读者可以了解像Windows这样的复杂操作系统是如何在x86处理器上运行的。 ......一起来看看 《Windows内核原理与实现》 这本书的介绍吧!

Markdown 在线编辑器
Markdown 在线编辑器

Markdown 在线编辑器

html转js在线工具
html转js在线工具

html转js在线工具

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试