如何正确显示 <string, object> 对

How to correctly display a <string, object> pair

所以,我 运行 在一个 class 中介绍了 IDictionary 的 C# 在线课程,他们在那里做了这个(用于测试包含字符串和 class):

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

    }

应该显示对的内容

[Ex1, {Example 1, 34672}]

但是,它显示给我:

[Ex1, ConsoleApp1.Program+Student]

这是视频的直接复制,所以我认为这可能是 .NET 框架版本的一些差异,但不是。刚刚前往 SO 看看我是不是疯了。我可以使用 item.Value.v1 获取值,但这需要对现实生活中的实例做太多工作,因为我将不得不 运行 遍历该对象内的所有值。

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

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

在您的 Student class 中,您需要为 ToString() 方法添加一个覆盖,因为它当前正在返回 base.ToString(),这是对象的命名本身,而不是其中包含的对象(string v1int v2)。

将此添加到您的 Student class:

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

基本上,object.ToString() 将 return 输入。 如果你想要不同的东西,你可以覆盖 ToString() 方法

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

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}}}";
    }
}

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