gpt4 book ai didi

c# - 将字符串数组分配给列表

转载 作者:太空宇宙 更新时间:2023-11-03 18:45:26 25 4
gpt4 key购买 nike

我在运行这段代码时遇到了 Stackoverflow

class Students
{
public int SID { get { return SID; } set { SID = value; } }
public string SName { get { return SName; } set { SName = value; } }
}

问题出在 foreach(string s in names).. 我无法将字符串数组存储到我的数据结构中提前致谢

 class Program
{
static void Main(string[] args)
{
List<Students> sList = new List<Students>();
string[] names = new string[5] {"Matt", "Joanne", "Robert"};
System.Console.WriteLine("{0} words in text:", names.Length);

foreach (string s in names)
{
Students st = new Students();
st.SName = s;
sList.Add(st);
System.Console.WriteLine("test{0}",s);
}

foreach (Students sn in sList) Console.WriteLine(sn);

Console.ReadLine();
}
}

最佳答案

public int SID 
{
get
{
//here you try to return SID, again the "get" method is called
//hence the StackOverflowException
return SID;
}
set
{
//same issue here
SID = value;
}
}

将您的代码更改为:

public int SID { get; set; }

或使用字段:

private int _SID;
public int SID
{
get
{
return _SID;
}
set
{
_SID = value;
}
}

关于c# - 将字符串数组分配给列表<myclass>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4720631/

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