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

时间:2011-04-09 10:01:55

标签: c# visual-studio-2010 extension-methods debuggervisualizer debuggerdisplay

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

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

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

作为一个例子,我试图显示更短的类型名称,例如$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

但是调试器抱怨:当前上下文中不存在名称“ShortName”。

我是否遗漏了某些内容,或者是否无法在那里使用扩展方法?

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

3 个答案:

答案 0 :(得分: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();
    }    
}

答案 1 :(得分:4)

简而言之,没有。出于同样的原因,扩展方法不能使用dynamic,而只是方法名称,因此无法知道using指令是什么实际上,因此哪种扩展方法是候选者。完全有可能使用不同的using指令更改可用方法,因此尝试猜测没有任何好处。

除非字符串允许您明确指定类上的静态方法,即DbgDisp.Ext.ShortName(foo),否则您必须限制自己使用常规方法。

答案 2 :(得分:0)

您可以在类中放置一个私有方法,该方法使用您想要生成字符串的扩展方法。然后,DebuggerDisplay属性可以引用该方法。