【问题标题】:Cannot print elements from the list无法打印列表中的元素
【发布时间】:2021-03-20 09:24:45
【问题描述】:
public class item
{
  public int x;  
  public string s;
  public item ()
  {}
}

然后在 main 方法中,我尝试创建一个列表并打印出其中的元素。

{
  item first=new item();
  first.x=5;
  first.s="Hello";
 
  item second =new item();
  second.x=6;
  second.s="world";

  List <item> myItem= new List <item> ();
  myItem.Add(first);
  myItem.Add(second);
  
  foreach (item element in myItem)
  {
    Console.WriteLine(element);
  }
}

没有语法错误,但是当我尝试运行上面的代码时,终端没有返回任何内容。

【问题讨论】:

  • 尝试使用你的对象字段,Console.WriteLine("x: " + element.x.ToString() + " s: " + element.s);这可能会有所帮助stackoverflow.com/questions/360277/…
  • 请提供minimal reproducible example 而不是sn-ps。我希望打印item 两次,因为ToString() 的默认实现只返回类名。 (顺便说一句,我强烈建议尽早学习并遵循 C# 命名约定。)
  • “没有语法错误” false。这不编译。 first.x=5; 将不起作用,因为 int x 没有定义访问器,因此是私有的。而你正在使用y,它没有被定义。
  • 我修正了错字并在字段变量中添加了访问修饰符,以免混淆,谢谢。
  • 我们仍然缺少minimal reproducible example。同样,我希望它会打印两次item。如果它没有为您打印任何内容,则可能还有其他问题……但如果我们无法重现它,我们将无法帮助您。

标签: c# list


【解决方案1】:

编译器不会神奇地知道如何将自定义类型转换为字符串。但是,每个类都派生自 object 类,该类具有(虚拟)ToString 方法。如果没有被覆盖,它将打印类名。 您可以在item 类中使用override it yourself。例如

public override string ToString()
{
    return "x: " + x + ", s: " + s;
}

【讨论】:

    【解决方案2】:

    您所遵循的方法可以改进。看到这个—— Getter and Setter declaration in .NET

    你已经在类中定义了变量

    int x;
    string s;
    

    并用作

    first.x=5;
    first.y="Hello"; // what is y here? It is not defined in your model class
    

    在您的方法中,列表元素可以像这样打印(当前项目类中的属性是私有的,您已将它们设为公开或查看@jhbonarius 对 toString 方法的回答)

    foreach (item element in myItem)
      {
        Console.WriteLine(element.x +" "+element.s);
      }
    

    【讨论】:

    • 没有。如果未定义访问器,则默认为私有。所以 x 和 s 不能从类外部访问
    • 是的,谢谢@JHBonarius,我已经在答案中指出了这一点。
    • 感谢 @Abhishek 和 JHBonarius 指出问题。所以这句话只能用'Console.WriteLine(element);'当列表中的项目是相同的变量类型时,即全部为 int 或全部为字符串?
    【解决方案3】:

    请使用 PascalCase 来定义类和字段。

    public class Item
    {
        public string A { get; set; }
        public int X { get; set; }
    }
    

    WriteLine 方法自动调用 ToString 方法将对象“转换”为字符串。

    如果要查看必须写的字段的值:

    Console.WriteLine(“A: ” + item.A + “ X: “ + item.X);
    // or w/ string interpolation
    Console.WriteLine($”A: {item.A} X: {item.X}”);
    
    // console output
    A: ‘value of A’ X: ‘value of X’
    

    您还可以覆盖“Item”类中的 ToString 方法。

    public class Item
    {
        public string A { get; set; }
        public int X { get; set; }
    
        public override string ToString()
        {
            return "A: " + A + " X: " + X;
        }
    }
    

    要在控制台上写入值,只需写入

    Console.WriteLine(item);
    
    // console output
    A: ‘value of A’ X: ‘value of X’
    

    【讨论】:

      【解决方案4】:

      您遇到的问题是您正在尝试打印整个项目。 如果您在“项目”类中实现 ToString() 方法(如上面 JHBonarius 的答案),然后调用:

      foreach (item element in myItem)
      {
          Console.WriteLine(element.ToString()); .
      }
      

      或者您尝试打印“项目”的确切属性,例如:

      foreach (item element in myItem)
      {
          Console.WriteLine("x: " + element.x.ToString() + " s: " element.s.ToString()); 
      }
      

      并且绝对将您的类定义更改为上面@SteeBono 推荐的定义。

      public class item
      {
          public int x { get; set; }
          public string s { get; set; }
      }
      

      如果您想动态打印出您的属性,您可以使用遍历类的所有属性(在本例中为“item”):

      foreach (var element in myItem)
      {
          elementPrintData += "Element : \n";
      
          foreach (var fromProp in typeof(item).GetProperties())
          {
              var toProp = typeof(item).GetProperty(fromProp.Name);
              var toValue = toProp.GetValue(element, null);
              string val = "";
              if (toValue != null)
              {
                  // this will try to print DateTime if present, might need to add null check
                  if (toProp.PropertyType == typeof(DateTime?) || toProp.PropertyType == typeof(DateTime))
                      val = ((DateTime)toValue).ToString("dd/MM/yyyy");
                  else
                      val = toValue.ToString();
              }
      
          // this will print the property name with the value (int, string, bool, double...) 
          //if it is not a collection/list
          // each property will go into a new line because of the " \n"
              if (!string.IsNullOrEmpty(val) && !val.Contains("System.Collections"))
                  elementPrintData += toProp.Name + ": " + val + " \n";
         }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-10-11
        • 1970-01-01
        • 1970-01-01
        • 2022-01-23
        • 2015-07-28
        • 2018-07-22
        • 1970-01-01
        相关资源
        最近更新 更多