在[DebuggerDisplay]属性中使用扩展方法

Mil*_*lKa 8 c# extension-methods visual-studio-2010 debuggervisualizer debuggerdisplay

Attribute [DebuggerDisplay](使用DebuggerDisplayAttribute)允许在VS 2010/2008的调试器中定义显示.通过修改AutoExp.cs/.dll,我甚至可以覆盖系统类型和第三方类型的显示,例如

[assembly: DebuggerDisplay (@"\{Name = {Name} FullName = {FullName}}", Target = typeof (Type))]
Run Code Online (Sandbox Code Playgroud)

在内部花括号中,我可以引用字段,属性和方法.是否可以引用扩展方法

作为一个例子,我试图显示更短的类型名称,例如,$SCG.Dictionary而不是System.Collections.Generic.Dictionary.我将此添加到AutoExp.cs:

using DbgDisp;

[assembly: DebuggerDisplay (@"\{Name = {Name} ShortName = {ShortName()}}", Target = typeof (Type))]

namespace DbgDisp {
  public static class Ext {
    public static string ShortName (this Type t) { return string.Format ("[{0}]", t.Name); }
  } // Ext
} // DbgDisp
Run Code Online (Sandbox Code Playgroud)

但调试器抱怨:当前上下文中不存在名称"ShortName".

我错过了什么,或者只是不可能在那里使用扩展方法?

我知道我可以覆盖ToString (),但这只对我自己的类型有帮助.

see*_*per 6

实际上你可以使用传递它的扩展方法作为参数

[assembly: DebuggerDisplay(@"NetGuid = {ToString()} OracleGuid = {GuidExtensions.ToVarChar(this)}", Target = typeof(Guid))]
public static class GuidExtensions
{
    public static string ToVarChar(this Guid guid)
    {
        var newBytes = new byte[16];
        var oldBytes = guid.ToByteArray();
        for (var i = 8; i < 16; i++)
            newBytes[i] = oldBytes[i];

        newBytes[3] = oldBytes[0];
        newBytes[2] = oldBytes[1];
        newBytes[1] = oldBytes[2];
        newBytes[0] = oldBytes[3];
        newBytes[5] = oldBytes[4];
        newBytes[4] = oldBytes[5];
        newBytes[6] = oldBytes[7];
        newBytes[7] = oldBytes[6];

        return new Guid(newBytes).ToString("N").ToUpper();
    }    
}
Run Code Online (Sandbox Code Playgroud)

  • 非常感谢,这工作得很好(至少在 VS2017 中)。其他人请注意:您的“[Assembly:”属性未在任何命名空间中定义,因此您必须完全指定该类型的命名空间。即 `MyCompany.MyProduct.Utils.GuidExtensions.ToVarChar(this)` (2认同)

Mar*_*ell 5

简而言之,没有。出于相同的原因,扩展方法不适用于dynamic,即仅从方法名称,无法知道哪些using指令有效,因此无法知道哪些扩展方法是候选者。完全有可能出现使用不同using指令更改可用方法的场景,因此尝试猜测没有任何好处。

您必须将自己限制为常规方法,除非该字符串允许您在类上明确指定静态方法,即DbgDisp.Ext.ShortName(foo).