在 C# 的列表中设置 get class
set get class in list in c#
我在下面写了代码,其中我使用 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));
}
}
}
代码运行时出现异常:
Exception of type 'System.WhosebugException' was thrown`.
如何解决问题?
当您调用 Name get 属性 时,您的代码显示“通过调用 Name get 属性 获取名称”,系统陷入无限循环。同样,您的集合 属性 告诉系统再次调用集合 属性。
改变
public string Name { get { return Name; } set { Name = Id.ToString(); }
至
public string Name { get { return Id.ToString(); } }
我在下面写了代码,其中我使用 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));
}
}
}
代码运行时出现异常:
Exception of type 'System.WhosebugException' was thrown`.
如何解决问题?
当您调用 Name get 属性 时,您的代码显示“通过调用 Name get 属性 获取名称”,系统陷入无限循环。同样,您的集合 属性 告诉系统再次调用集合 属性。
改变
public string Name { get { return Name; } set { Name = Id.ToString(); }
至
public string Name { get { return Id.ToString(); } }