类的C#可选数组参数 [英] C# Optional Array Parameter for Class

查看:69
本文介绍了类的C#可选数组参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道可以使用null完成此操作,因此我有一种解决方法,但是我想知道是否有更好的方法可以为类提供可选的int[]参数?

I know this can be done using null so I have a workaround for that, but I was wondering if there was a better way that I can have an optional int[] parameter for a class?

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

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

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

This gives me an error saying it is an invalid expression defaultPriceLevels must be constant. How can I fix this?

我可以解决的一个办法是,但是我真的不喜欢该解决方案

One workaround that I can thing of is this, but I don't really like the solution

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个构造函数(

A better design all together would be to have 2 constructors (constructor overload) one that gets a int[] and another that doesn't:

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;
    }
}

否则,不知道我是否称其为更好",但是您可以使用

If not, don't know if i'd call this "better" but you can use the params keyword:

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是责任,并且无论如何都应将其作为依赖项-请参见

Also, depending on design, I'm not convinced that it is PriceLevels responsibility to decide what the default values are and maybe it should get it as a dependency in any case - See SOLID and Dependency Injection. Then you'd have only 1 constructor:

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

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

这篇关于类的C#可选数组参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆