StackOverflow来自get和set的异常

use*_*358 4 c# get set

我有以下代码:

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);
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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

我知道这是因为我没有做正确的设置并且正在进入无限循环,但我不明白为什么会发生这种情况?

Jon*_*lis 9

public DateTime time
{
    get { return this.time; }
    set
    {
        this.time = value;                
    }
}
Run Code Online (Sandbox Code Playgroud)

您没有使用支持字段,而是在属性设置器中设置属性本身.

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

public DateTime Time { get; set; }
Run Code Online (Sandbox Code Playgroud)

或2)支持领域

private DateTime _time;
public Datetime Time 
{
    get { return _time; }
    set { _time = value; }
} 
Run Code Online (Sandbox Code Playgroud)

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

要获得解释,当您进入time代码时:

get { return this.time; } 
Run Code Online (Sandbox Code Playgroud)

它必须检索time要返回的值.它通过调用geton来实现time,必须获取其值time,等等.