我可以在我不拥有的类型上使用 DebuggerTypeProxyAttribute 之类的东西吗?

Rog*_*mbe 4 visual-studio-debugging visual-studio-2012

我有一个IClaimsPrincipal变量,我想看看其中有多少个声明。在监视窗口中导航属性很复杂,因此我想自定义该对象的显示方式。

我知道这个[DebuggerTypeProxy]attribute,它最初看起来可能会做我想要的事情。不幸的是,它需要附加到课程中,而我并不“拥有”该课程。在本例中,它是一个Microsoft.IdentityModel.Claims.ClaimsPrincipal.

我想显示 的值IClaimsPrincipal.Identities[0].Claims.Count

有没有任何方法(使用[DebuggerTypeProxy]或类似的方法)来自定义我不拥有的类型的值在监视窗口中的显示方式?

Jen*_*ens 5

更新:正如 Sod Almigthy 所指出的,这不适用于 VS2022


应用于 KeyValuePair 的DebuggerTypeProxyAttribute示例仅显示 Value 成员:

using System.Collections.Generic;
using System.Diagnostics;

[assembly: DebuggerTypeProxy(typeof(ConsoleApp2.KeyValuePairDebuggerTypeProxy<,>), Target = typeof(KeyValuePair<,>))]
// alternative format [assembly: DebuggerTypeProxy(typeof(ConsoleApp2.KeyValuePairDebuggerTypeProxy<,>), TargetTypeName = "System.Collections.Generic.KeyValuePair`2")]

namespace ConsoleApp2
{
    class KeyValuePairDebuggerTypeProxy<TKey, TValue>
    {
        private KeyValuePair<TKey, TValue> _keyValuePair; // beeing non-public this member is hidden
        //public TKey Key => _keyValuePair.Key;
        public TValue Value => _keyValuePair.Value;

        public KeyValuePairDebuggerTypeProxy(KeyValuePair<TKey, TValue> keyValuePair)
        {
            _keyValuePair = keyValuePair;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            var dictionary = new Dictionary<int, string>() { [1] = "one", [2] = "two" };
            Debugger.Break();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

在 Visual Studio 2017 上测试