【问题标题】:set get class in list in c# [duplicate]在c#中的列表中设置获取类[重复]
【发布时间】:2021-05-08 08:20:32
【问题描述】:

我在下面编写了代码,我使用Id 填写名称。

namespace ConsoleApp1
{
    class test
    {
        public int Id { get; set; }
        public string Name { get { return Name; } set { Name = Id.ToString(); } }
    }
    class Program
    {
        static void Main(string[] args)
        {

            List<test> t1 = new List<test>();

            t1.Add(new test() { Id = 1 });
            t1.Add(new test() { Id = 2 });
            t1.Add(new test() { Id = 3 });
            t1.Add(new test() { Id = 4 });
            t1.Add(new test() { Id = 5 });

            Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(t1));
        }
    }
}

代码运行时,抛出异常:

抛出了“System.StackOverflowException”类型的异常`。

如何解决问题?

【问题讨论】:

    标签: c# class get set


    【解决方案1】:

    当您调用 Name 获取属性时,您的代码会显示“通过调用 Name 获取属性来获取名称”,并且系统会陷入无限循环。同样,您的 set 属性告诉系统再次调用 set 属性。

    改变

    public string Name { get { return Name; } set { Name = Id.ToString(); } 
    

    public string Name { get { return Id.ToString(); } } 
    

    【讨论】:

    • 更短的版本是public string Name =&gt; $"{Id}";
    猜你喜欢
    • 1970-01-01
    • 2010-12-22
    • 2013-04-02
    • 2013-09-25
    • 2011-09-16
    • 2014-04-25
    • 2014-02-07
    • 1970-01-01
    • 2011-09-24
    相关资源
    最近更新 更多