Visual Studio 2010中的监视窗口不适用于从通用Dictionary继承的类

时间:2013-09-12 13:05:17

标签: c# visual-studio-2010 dictionary tostring visual-studio-debugging

我创建了一个继承自Dictionary<string, string>并重写方法ToString()的类,以便于调试(在Watch窗口中查看此类实例的状态)。如果我在控制台上显示这种类型,一切正常:

Displaying custom type that inherited from Dictionary<string, string> in Console

但似乎Visual Studio仍然使用ToString()类型的原始方法Dictionary<string, string>

Displaying custom type that inherited from Dictionary<string, string> in Watch window

这个事实使我的代码调试变得非常复杂,因为我无法快速查看此类字段的所需值。

如何强制Visual Studio使用我的方法ToString(),而不是Dictionary<string, string>类型的方法?

using System;
using System.Collections.Generic;

namespace TestDictionary
{
    class Program
    {
        static void Main(string[] args)
        {
            CmdValue innerCmdVal = new CmdValue("InnerName", null);
            CmdValue cmdVal = new CmdValue("name1", innerCmdVal);
            cmdVal.Add("key1", "value1");
            Console.WriteLine(cmdVal);
            Console.ReadKey();
        }
    }

    class CmdValue : Dictionary<string, string>
    {
        public readonly string Name;
        public readonly CmdValue InnerCmdValue;

        public CmdValue(string name, CmdValue innerCmdValue)
        {
            this.Name = name;
            this.InnerCmdValue = innerCmdValue;
        }

        public override string ToString()
        {
            string str = string.Format("{0}[{1}].{2}", this.Name, this.Count, this.InnerCmdValue);
            return str;
        }
    }
}

1 个答案:

答案 0 :(得分:1)

您正在寻找DebuggerDisplayAttribute

示例:

[DebuggerDisplay("Name: {LastName}, {FirstName}")]
public class Customer
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

如果您创建名为Bill Clinton的客户,调试器窗口将显示“Name:Clinton,Bill”作为值。