gpt4 book ai didi

c# - 验证值的优雅方式

转载 作者:太空狗 更新时间:2023-10-29 17:39:34 25 4
gpt4 key购买 nike

我有一个包含许多代表不同物理值的字段的类。

class Tunnel
{
private double _length;
private double _crossSectionArea;
private double _airDensity;
//...

每个字段都使用读/写属性公开。我需要检查 setter 值是否正确,否则会生成异常。所有的验证都是相似的:

    public double Length
{
get { return _length; }
set
{
if (value <= 0) throw new ArgumentOutOfRangeException("value",
"Length must be positive value.");
_length = value;
}
}

public double CrossSectionArea
{
get { return _crossSectionArea; }
set
{
if (value <= 0) throw new ArgumentOutOfRangeException("value",
"Cross-section area must be positive value.");
_crossSectionArea = value;
}
}

public double AirDensity
{
get { return _airDensity; }
set
{
if (value < 0) throw new ArgumentOutOfRangeException("value",
"Air density can't be negative value.");
_airDensity = value;
}
}
//...

有没有优雅灵活的方式来完成这样的验证?

最佳答案

假设您想要这种行为,您可能会考虑一些辅助方法,例如

public static double ValidatePositive(double input, string name)
{
if (input <= 0)
{
throw new ArgumentOutOfRangeException(name + " must be positive");
}
return input;
}

public static double ValidateNonNegative(double input, string name)
{
if (input < 0)
{
throw new ArgumentOutOfRangeException(name + " must not be negative");
}
return input;
}

然后你可以这样写:

public double AirDensity
{
get { return _airDensity; }
set
{
_airDensity = ValidationHelpers.ValidateNonNegative(value,
"Air density");
}
}

如果您需要它用于各种类型,您甚至可以将其设为通用:

public static T ValidateNonNegative(T input, string name)
where T : IComparable<T>
{
if (input.CompareTo(default(T)) < 0)
{
throw new ArgumentOutOfRangeException(name + " must not be negative");
}
return input;
}

请注意,这些都不是非常适合 i18n 的...

关于c# - 验证值的优雅方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6666264/

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