抛出了类型为'System.StackOverflowException'的异常。

20

我的程序抛出了以下异常:

System.StackOverflowException

当编译器执行设置属性时。

wine类:

class wine
{
    public int year;
    public string name;
    public static int no = 5;

    public wine(int x, string y)
    {
        year = x;
        name = y;
        no++;
    }

    public int price
    {
        get
        {
            return no * 5;
        }

        set
        {
            price = value;
        }
    }
}

Program 类:

class Program
{
    static void Main(string[] args)
    {
        wine w1 = new wine(1820, "Jack Daniels");

        Console.WriteLine("price is " + w1.price);
        w1.price = 90;
        Console.WriteLine(w1.price);
        Console.ReadLine();
    }
}

2
你需要使用一个后备字段,例如 private int _price,然后将其设置为值,例如 set { _price = value; } - DGibbs
3个回答

26

设置价格属性时,您调用了 setter,setter 又会调用 setter,以此类推。

解决方案:

public int _price;
public int price
{
    get
    {
        return no * 5;
    }

    set
    {
        _price = value;
    }
}

13

你正在setter中设置setter的值,这是一个无限循环,因此会触发StackOverflowException。

你可能想使用后备字段no,就像getter中一样:

public int price
{
    get
    {
        return no * 5;
    }

    set
    {
        no = value/5;
    }
}

或者使用它自己的后备字段。

private int _price;
public int price
{
    get
    {
        return _price;
    }

    set
    {
        _price = value;;
    }
}

然而,如果是后者的情况,您根本不需要备份字段,可以使用自动属性:

public int price { get; set; } // same as above code!

(顺带一提:属性应该以大写字母开头-Price而不是price)


1
您的属性设置器在设置任何值时会调用自身,从而导致堆栈溢出。我认为您想要做的是:
public int price
{
    get
    {
        return no * 5;
    }

    set
    {
        no = value / 5;
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接