【问题标题】:How to correctly display a <string, object> pair [duplicate]如何正确显示 <string, object> 对 [重复]
【发布时间】:2018-06-06 10:35:08
【问题描述】:

所以,我在一堂介绍 IDictionary 的课程中​​学习了 C# 在线课程,他们这样做了(用于测试包含字符串和类实例的对):

    public static void Main(string[] args)
    {

        IDictionary<string, Student> Students = new Dictionary<string, Student>();

        Students.Add("Ex1", new Student("Example 1", 34672 ));
        Students.Add("Ex2", new Student("Example 2", 8787));

        foreach (var item in Students)
        {
            Console.WriteLine(item);
        }
        Console.ReadKey();
    }

    public class Student
    {
        public string v1 { get; set; }
        public int v2 { get; set; }

        public Student (string v1, int v2)
        {
            this.v1 = v1;
            this.v2 = v2;
        }

    }

应该显示pair的内容

[Ex1, {Example 1, 34672}]

但相反,它向我展示了:

[Ex1, ConsoleApp1.Program+Student]

这是视频的直接副本,所以我认为这可能是 .NET 框架版本的一些差异,但不是。只是去看看我是不是疯了。我可以使用 item.Value.v1 获取值,但这需要在现实生活中的实例上做太多工作,因为我必须遍历该对象内的所有值。

【问题讨论】:

  • 您可以在 Student 类中覆盖 .ToString()。否则,对象的默认字符串表示是它的类名。
  • 谢谢,大卫。我知道有些事情没有加起来。讲师正在编译并获得正确的显示,没有任何覆盖。希望我可以将您的评论标记为答案,因为您是第一个提供此解决方案(有效)的人。
  • Sebastian 的答案应该被标记为答案,因为他是第一个用答案而不是评论做出回应的人。非常不言自明的系统。
  • 是的。我知道系统是如何工作的,但尽管如此.. 大卫确实比塞巴斯蒂安早 2 分钟提供了答案。他只是没有发布任何代码。我只是感谢他是第一个。顺便说一句,我可以选择你的或 Rawita 的,因为你们都不仅提供了代码,还提供了背后的原因。所以,谢谢大家。

标签: c# idictionary


【解决方案1】:

您可以覆盖 Student 类中的 ToString() 方法

public override string ToString()
{
    return "{" + v1 + "," + v2 + "}";
}

【讨论】:

    【解决方案2】:

    在您的Student 类中,您需要为ToString() 方法添加一个覆盖,因为它当前返回base.ToString(),它是对象本身的名称,而不是其中包含的对象(@ 987654323@ 和 int v2)。

    在你的 Student 类中添加这个:

    public override string ToString()
    {
         return "{" + v1 + "," + v2.ToString() + "}";
    }
    

    【讨论】:

      【解决方案3】:

      基本上,object.ToString() 将返回类型。 如果你想要不同的东西,你可以覆盖 ToString() 方法

      这是ToString()object类中的实现;

      public virtual String ToString()
      {
          return GetType().ToString();
      }
      

      所以把你的代码改成

      public class Student
      {
          public string v1 { get; set; }
          public int v2 { get; set; }
          public Student(string v1, int v2)
          {
              this.v1 = v1;
              this.v2 = v2;
          }
          public override string ToString()
          {
              return $"{{{v1}, {v2}}}";
          }
      }
      

      【讨论】:

        【解决方案4】:

        尝试分别显示 item.key 和 item.value

        【讨论】:

        • 在他的Student 类中没有keyvalue 属性,但是v1v2
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-08-07
        • 2021-07-27
        • 2019-12-27
        • 2018-08-07
        • 2020-06-24
        • 1970-01-01
        相关资源
        最近更新 更多