【问题标题】:assign string arrays to list<myclass>将字符串数组分配给 list<myclass>
【发布时间】:2011-01-18 05:01:54
【问题描述】:

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

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

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

 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();
     }
 }

【问题讨论】:

  • 您是否面临空引用异常

标签: c# arrays list


【解决方案1】:
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; 
  } 
}

【讨论】:

    【解决方案2】:
    public int SID { get { return SID; } set { SID = value; } }
    

    想一想那里发生了什么? 想一想那里发生了什么? 想一想那里发生了什么? 想一想那里发生了什么? 想一想那里发生了什么? 想一想那里发生了什么? 想一想那里发生了什么? 想一想那里发生了什么? 想一想那里发生了什么?

    【讨论】:

    • 在google上搜索关键字recursion,会提示“你的意思是recursion吗?” :D
    【解决方案3】:

    SID 属性不是问题,因为您的代码从不调用它。 SName 属性是导致堆栈溢出的属性。改成

    public string SName { get; set; }

    所以它不引用自身。

    names 被声明为 string[5] 但仅使用 3 个名称进行初始化。将其更改为 string[3] 或添加另外两个名称。

    您还会发现Console.WriteLine(sn); 为每个学生输出相同的班级名称AppName.Students,而不是有用的学生信息。可以通过在 Student 类中添加类似的内容来解决此问题

    public override string ToString() { return SID + " " + SName; }

    这会覆盖作为每个 .NET 对象一部分的默认 ToString 方法,并改为显示您指定的任何内容。为了使本示例正常运行,您还需要将 SID 属性更新为 public string SID { get; set; } 以避免更多的堆栈溢出。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-10-09
      • 2021-12-07
      • 2021-07-23
      • 2015-06-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多