简体   繁体   English

C# 如何使用可选值将属性传递给基础 class?

[英]C# How to pass properties to base class with optional values?

In the code example below, if HighValue and LowValue properties are not set by the client, how can I pass default values for these properties to the base class?在下面的代码示例中,如果客户端未设置 HighValue 和 LowValue 属性,我如何将这些属性的默认值传递给基本 class?

If there is a design mistake in this example setup, I'd like to thank you in advance for warning me.如果此示例设置中存在设计错误,我要提前感谢您警告我。


public class Foo
{
    public Foo(int scaleHigh, int scaleLow)
    {
        ScaleHigh = scaleHigh;
        ScaleLow = scaleLow;
    }

    public int ScaleHigh { get; }
    public int ScaleLow { get; }
}


public class Bar : Foo
{
    public Bar(Bar bar)
        : base(bar.ScaleHigh, bar.ScaleLow)
    {
        HighValue = SomeHelper.ReCalculate(bar.HighValue);
        LowValue = SomeHelper.ReCalculate(bar.LowValue);
    }

    public int HighValue { get; }
    public int LowValue { get; }
}


public class SomeHelper
{
    public static int ReCalculate(int scale)
    {
        return scale * 5;
    }
}


public class Client : Bar
{
    public Client(Bar bar) : base(bar) { }

    public int Request(bool condition)
    {
        return condition ? HighValue : LowValue;
    }
}

you have a bug in your bar class, since it doesn't have a default constructor, you will never be able to create the object, since it will be a recursion forever - each new instance would neeed another and so on您的酒吧 class 中有一个错误,因为它没有默认构造函数,您将永远无法创建 object,因为它将永远是一个递归 - 每个新实例都需要另一个,依此类推

public class Bar : Foo
{
    public Bar(Bar bar)
        : base(bar.ScaleHigh, bar.ScaleLow)
    {
        HighValue = SomeHelper.ReCalculate(bar.HighValue);
        LowValue = SomeHelper.ReCalculate(bar.LowValue);
    }

    public int HighValue { get; }
    public int LowValue { get; }
}

you can fix it by adding another constructor like this您可以通过添加另一个像这样的构造函数来修复它

public Bar(int scaleHigh=0, int scaleLow=0, int highValue=0, int lowValue=0)
        : base(scaleHigh, scaleLow)
    {
        HighValue = SomeHelper.ReCalculate(highValue);
        LowValue = SomeHelper.ReCalculate(lowValue);
    }

Sorry if I misunderstand, but I believe you want to set default values of Bar if they are not set?对不起,如果我误解了,但我相信你想设置 Bar 的默认值,如果它们没有设置? In what case would the constructor not set the values?在什么情况下构造函数不会设置值?

In the case that you didn't set those in your constructor, one thing you can consider is making the types int?如果您没有在构造函数中设置它们,您可以考虑的一件事是将类型设置为int? and then set the variable like this:然后像这样设置变量:

public int? HighValue => HighValue?? (defaultValue)

Try this:尝试这个:

public int LowValue { get; } = 0; //You can change these values.
public int HighValue { get; } = 10;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM