gpt4 book ai didi

c# - 来自 get 和 set 的 StackOverflow 异常

转载 作者:太空狗 更新时间:2023-10-30 00:04:44 25 4
gpt4 key购买 nike

我有以下代码:

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);
}
}
}
}

但是我得到一个堆栈溢出异常。

我知道这是因为我没有正确执行 get 和 set 并进入了无限循环,但我不明白为什么会这样?

最佳答案

public DateTime time
{
get { return this.time; }
set
{
this.time = value;
}
}

您没有使用支持字段,而是从属性 setter 中设置属性本身。

您可以通过使用 1) 自动属性来解决此问题

public DateTime Time { get; set; }

或 2) 支持字段

private DateTime _time;
public Datetime Time
{
get { return _time; }
set { _time = value; }
}

它们都等同于相同的代码。

为了解释,当你在代码中得到 time 时:

get { return this.time; } 

它必须检索 time 的值才能返回。它通过在 time 上调用 get 来做到这一点,它必须获取 time 的值,等等。

关于c# - 来自 get 和 set 的 StackOverflow 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32977482/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com