c#中的动态类构造函数

Hou*_*ami 3 c# oop constructor class

我有一个类有2个属性,名为MinValue,MaxValue,如果有人想要调用这个类并实例化这个类,我需要一些允许选择MinValue或Max Value或它们两者的构造函数,它们的MinValue和MaxValue都是int,所以构造函数不允许我这样:

public class Constructor
{
    public int Min { get; set; }
    public int Max { get; set; }
    public Constructor(int MinValue, int MaxValue)
    {
        this.Min = MinValue;
        this.Max = MaxValue;
    }

    public Constructor(int MaxValue)
    {
        this.Max = MaxValue;
    }

    public Constructor(int MinValue)
    {
        this.Min = MinValue;
    }
}
Run Code Online (Sandbox Code Playgroud)

现在我不能这样做因为我不能重载两个构造函数,我该如何实现呢?

Jon*_*eet 6

我会为你只有部分信息的两个部分创建两个静态方法.例如:

public Constructor(int minValue, int maxValue)
{  
    this.Min = minValue;
    this.Max = maxValue;
}

public static Constructor FromMinimumValue(int minValue)
{
    // Adjust default max value as you wish
    return new Constructor(minValue, int.MaxValue);
}

public static Constructor FromMaximumValue(int maxValue)
{
    // Adjust default min value as you wish
    return new Constructor(int.MinValue, maxValue);
}
Run Code Online (Sandbox Code Playgroud)

(使用命名参数的C#4选项也很好,但前提是您知道所有调用者都支持命名参数.)