类的C#可选数组参数 [英] C# Optional Array Parameter for Class
问题描述
我知道可以使用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;
}
}
推荐答案
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
是责任,并且无论如何都应将其作为依赖项-请参见依赖注入 .那么您只有1个构造函数:
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屋!