优雅的方式来验证价值观

Kyr*_*o M 9 .net c# validation

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

class Tunnel
{
    private double _length;
    private double _crossSectionArea;
    private double _airDensity;
    //...
Run Code Online (Sandbox Code Playgroud)

使用读/写属性公开每个字段.我需要检查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;
        }
    }
    //...
Run Code Online (Sandbox Code Playgroud)

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

Jon*_*eet 6

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

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;
}
Run Code Online (Sandbox Code Playgroud)

然后你可以写:

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

如果你需要各种类型,你甚至可以使它通用:

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;
}
Run Code Online (Sandbox Code Playgroud)

请注意,这些都不是非常友好的...