如何在C#中停止构造函数的工作?

如何在C#中停止构造函数的工作?,c#,C#,这是典型的课堂 class Round { private int radius; private bool Validate(int radius) { if (radius <= 0) { return false; } else { return true; } }

这是典型的课堂

class Round
{
    private int radius;

    private bool Validate(int radius) 
    {

            if (radius <= 0)
            {
            return false;
            }
            else
        {
            return true;
        }

    }

    public int X { get; set;}
    public int Y { get; set;}

    public int Radius
    {
        get
        {
            return radius;
        }

        set
        {
            try
            {   
                if(!Validate(value))
                {
                    throw new ArgumentException();
                }
            radius = value;
            }
            catch (ArgumentException)
            {

                Console.WriteLine("ooops... something went wrong.");
                return;
            }

        }
    }

    public Round (int X, int Y, int radius)
    {

        try
        {
            if (!Validate(radius))
            {
                throw new ArgumentException();
            }
        this.X = X;
        this.Y = Y;
        this.radius = radius;
        }
        catch (Exception)
        {

            Console.WriteLine("ooops... something went wrong.");
        }
    }

    public double GetPerimeter()
    {
        return Math.PI * radius * 2;
    }

}

class Program
{
    static void Main(string[] args)
    {
        Round r = new Round(0,0,0);
        Console.WriteLine(r.GetPerimeter());
    }
}
班级轮换
{
私有整数半径;
专用布尔验证(整数半径)
{

if(radius停止构造函数的方法是抛出异常


您正在这样做,但同时也在捕获异常。这样,构造函数将继续。不要捕获它。

停止构造函数的方法是抛出异常


你这样做,但是你也在捕捉异常。这样,构造函数就会继续。不要捕捉它。

如果你不想在构造函数中抛出异常,你可以考虑这个方法

// constructor
public Round (int X, int Y, int radius)
{
    this.X = X;
    this.Y = Y;
    this.radius = radius;
}

// create instance
public static Round CreateInstance(int X, int Y, int radius)
{
    if (!Validate(radius))
    {
        return null;
    }
    return new Round(X, Y, radius);
}
如何使用:

// invalid should be null
Round invalid = Row.CreateInstance(1, 1, -1);

如果你不想在构造函数中抛出异常,你可以考虑这个方法

// constructor
public Round (int X, int Y, int radius)
{
    this.X = X;
    this.Y = Y;
    this.radius = radius;
}

// create instance
public static Round CreateInstance(int X, int Y, int radius)
{
    if (!Validate(radius))
    {
        return null;
    }
    return new Round(X, Y, radius);
}
如何使用:

// invalid should be null
Round invalid = Row.CreateInstance(1, 1, -1);

如果构造函数中发生意外情况,则抛出一个
异常
。如果不想抛出异常,则可以使用静态类方法生成类的实例(“工厂”)。您不能停止构造函数,但可以抛出异常。您可以对异常作出反应,并通过重新抛出异常使其传播到外部级别。在
catch
block replace
return
中,使用
throw
。如果构造函数中发生意外情况,则抛出
异常。如果不想抛出异常您可以使用一个静态类方法来生成类的实例(“工厂”)。您不能停止构造函数,但可以抛出异常您可以对异常作出反应,并通过重新引用它让它传播到外部级别。在
catch
中,块替换
返回
抛出