来自get和set的StackOverflow异常 [英] StackOverflow Exception from get and set
问题描述
I have the following code:
namespace QuantStrats
{
class Program
{
static void Main(string[] args)
{
string FilePath = "C:\\Users\\files\\DJ.csv";
StreamReader streamReader = new StreamReader(FilePath);
string line;
List<Data> Data = new List<Data>();
while ((line = streamReader.ReadLine()) != null)
{
Data Tick = new Data();
string [] values = line.Split(',');
Tick.SetFields(values[1], values[2]);
Data.Add(Tick);
}
for (int ii = 0; ii < Data.Count; ii++)
{
Data TickDataValues = new Data();
TickDataValues = Data[ii];
Console.Write("TIME :" + TickDataValues.time + " Price : " + TickDataValues.price + Environment.NewLine);
}
Console.ReadLine();
}
}
class Data
{
public DateTime time
{
get { return this.time; }
set
{
this.time = value;
}
}
public double price
{
get { return this.price; }
set
{
this.price = value;
}
}
public void SetFields(string dateTimeValue, string PriceValue)
{
try
{
this.time = Convert.ToDateTime(dateTimeValue);
}
catch
{
Console.WriteLine("DateTimeFailed " + dateTimeValue + Environment.NewLine);
}
try
{
this.price = Convert.ToDouble(PriceValue);
}
catch
{
Console.WriteLine("PriceFailed " + PriceValue + Environment.NewLine);
}
}
}
}
但我得到一个堆栈溢出异常。
But I get a stack overflow exception.
我知道这是因为我没有做我的get和设置正确,并且正在进入一个无限循环,但我不明白为什么这个正在发生?
I know it is because I am not doing my get and sets correctly and am entering an infinite loop, but I cannot see why exactly this is happening?
推荐答案
public DateTime time
{
get { return this.time; }
set
{
this.time = value;
}
}
你没有使用后备字段,但设置属性本身来自于属性setter。
you aren't using backing fields, but setting the property itself from within the property setter.
你可以通过使用1)一个自动属性来解决这个问题
You can fix this by using 1) an auto property
public DateTime Time { get; set; }
或者2)后台字段
or 2) a backing field
private DateTime _time;
public Datetime Time
{
get { return _time; }
set { _time = value; }
}
它们都等同于相同的代码。
they both equate to the same code.
有关解释,当您在代码中获得 time
时:
For an explanation, when you get time
in your code:
get { return this.time; }
必须检索 time
返回。它通过在 time
上调用 get
来完成,它必须检索的值,时间
等。
it has to retrieve the value of time
to return. It does that by calling the get
on time
, which has to get retrieve the value of time
, etc.
这篇关于来自get和set的StackOverflow异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!