当编译器执行set属性时,我的程序抛出此异常('System.StackOverflowException').
葡萄酒类:
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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
program.cs类:
class Program {static void Main(string [] args){
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();
}
}
Run Code Online (Sandbox Code Playgroud)
Eya*_*rry 16
设置price属性时,调用setter,它会调用调用setter的setter等.
解:
public int _price;
public int price
{
get
{
return no * 5;
}
set
{
_price = value;
}
}
Run Code Online (Sandbox Code Playgroud)
您正在设置器中设置setter的值.这是一个无限循环,因此是StackOverflowException.
您可能打算no根据您的getter 使用支持字段:
public int price
{
get
{
return no * 5;
}
set
{
no = value/5;
}
}
Run Code Online (Sandbox Code Playgroud)
或者可能使用自己的支持领域.
private int _price;
public int price
{
get
{
return _price;
}
set
{
_price = value;;
}
}
Run Code Online (Sandbox Code Playgroud)
但是,如果是后者,则根本不需要支持字段,可以使用auto属性:
public int price { get; set; } // same as above code!
Run Code Online (Sandbox Code Playgroud)
(旁注:属性应以大写开头 - Price不是price)