c# - 如何验证重载构造函数的输入?

标签 c# constructor-overloading

这是我的代码

public class MyClass
{
    int LeftPoints;
    int RightPoints;

    public MyClass(int points)
        : this (points, points)
    {
        if (points < 0)
            throw new ArgumentOutOfRangeException("points must be positive");
    }

    public MyClass(int leftPoints, int rightPoints)
    {
        if (leftPoints < 0)
            throw new ArgumentOutOfRangeException("leftPoints must be positive");
        if (rightPoints < 0)
            throw new ArgumentOutOfRangeException("rightPoints must be positive");
    }
}

很明显,如果我调用new MyClass(-1),它会抛出消息“leftPoints 必须为正”。

可以使用 : this (points,points) 重载第一个构造函数并且仍然获得“正确的”验证吗?

最佳答案

您无法通过从第一个构造函数调用第二个构造函数来实现这一点。

如果您追求的是代码重用,则可以采取不同的方法:

public MyClass(int points)
{
    if (points < 0)
        throw new ArgumentOutOfRangeException("points must be positive");
    Init(points, points);
}

public MyClass(int leftPoints, int rightPoints)
{
    if (leftPoints < 0)
        throw new ArgumentOutOfRangeException("leftPoints must be positive");
    if (rightPoints < 0)
        throw new ArgumentOutOfRangeException("rightPoints must be positive");
    Init(leftPoints, rightPoints);
}

private void Init(int leftPoints, int rightPoints)
{
    LeftPoints = leftPoints;
    RightPoints = rightPoints;
}

关于c# - 如何验证重载构造函数的输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26769666/

相关文章:

c# - 在 C# 中动态生成委托(delegate)类型

c# - 如何伪造数据 GridView 片段的可见性?

c# - 从浏览器控制我的应用程序?

c# - 如何在 C# 中的 Html.ActionLink 上使用 CSS

c# - 具有多级 DI 的 Quartz.Net 作业

C++ 0/1-argument 构造函数在传递给模板构造函数时未按预期链接

java - java中的构造函数重载

c++ - 将非 null 终止的 vector<char> 转换为字符串

c++ - 我可以将调用复制构造函数的两种语法分为两种不同的方法吗?

c++ - 为类重载 "*"运算符以返回类变量