assign string arrays to list<myclass>
I have faced an Stackoverflow when I run this code
class Students
{
public int SID { get { return SID; } set { SID = value; } }
public string SName { get { return开发者_Python百科 SName; } set { SName = value; } }
}
The problem is located in foreach(string s in names).. I could not store the string array into my datastructure thanks in advance
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;
}
}
change your code to:
public int SID { get; set; }
or use a field:
private int _SID;
public int SID
{
get
{
return _SID;
}
set
{
_SID = value;
}
}
public int SID { get { return SID; } set { SID = value; } }
Think for a moment what is happening there? Think for a moment what is happening there? Think for a moment what is happening there? Think for a moment what is happening there? Think for a moment what is happening there? Think for a moment what is happening there? Think for a moment what is happening there? Think for a moment what is happening there? Think for a moment what is happening there?
The SID property is not the problem since it is never called by your code. The SName property is the one causing the stack overflow. Change it to
public string SName { get; set; }
so it does not reference itself.
names
is declared as string[5]
but only initialized with 3 names. Change that to string[3]
or add two more names.
You will also find that Console.WriteLine(sn);
outputs the same class name AppName.Students for every student instead of useful student info. That is fixed by adding something like this to your Student class
public override string ToString() { return SID + " " + SName; }
This overrides the default ToString method that is part of every .NET object and displays whatever you specify instead. For this example to work you'll also want to update the SID property to public string SID { get; set; }
to avoid more stack overflows.
精彩评论