我运行此代码时遇到了Stackoverflow
class Students
{
public int SID { get { return SID; } set { SID = value; } }
public string SName { get { return SName; } set { SName = value; } }
}
Run Code Online (Sandbox Code Playgroud)
问题位于foreach(名称中的字符串)..我无法提前将字符串数组存储到我的数据结构中
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();
}
}
Run Code Online (Sandbox Code Playgroud)
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;
}
}
Run Code Online (Sandbox Code Playgroud)
将您的代码更改为:
public int SID { get; set; }
Run Code Online (Sandbox Code Playgroud)
或使用字段:
private int _SID;
public int SID
{
get
{
return _SID;
}
set
{
_SID = value;
}
}
Run Code Online (Sandbox Code Playgroud)