gpt4 book ai didi

c# - c#中的动态类构造函数

转载 作者:行者123 更新时间:2023-11-30 13:39:11 25 4
gpt4 key购买 nike

我有一个具有 2 个属性的类,称为 MinValue、MaxValue,如果有人想调用此类并实例化此类,我需要一些具有允许选择 MinValue 或 Max Value 或两者的构造函数,MinValue 和 MaxValue 两者其中有整数,所以构造函数不允许我这样:

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

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

最佳答案

我将为您仅获得部分信息的两个部分创建两个静态 方法。例如:

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

(使用命名参数的 C# 4 选项也很好,但只有您知道所有调用方都将支持命名参数。)

关于c# - c#中的动态类构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13433454/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com