10

Anyone know of any code that duplicates how the DebuggerDisplayAttribute parses and gathers the resultant string?

I would like to create a custom attribute that does nearly the sample thing. Similiar to "When a breakpoint is hit..." where you can use a variable within curly braces, as in "{variable}".

I already handle simple cases, such as "{Name}", but something like "{Foo.Name}" requires extra reflection code that I need help with.

Basically, I want to parse a string using the rules defined in the DebuggerDisplayAttribute documentation. Currently, I can parse and resolve "I am {GetName()}". I need help with something like "Foo's Name: {Foo.Name}"

4

2 回答 2

5

希望这段代码都适合...我使用 Microsoft Roslyn 及其 C# 脚本功能将属性值中的“代码”作为 C# 代码运行,制作了您正在尝试做的事情的非反射版本。

要使用此代码,请创建一个新的 C# 项目,并使用 NuGet 添加对 Roslyn 的引用。

首先是我用来测试的类,这样你就可以看到我尝试过的属性。

using System.Diagnostics;

namespace DebuggerDisplayStrings
{
    [DebuggerDisplay("The Value Is {StringProp}.")]
    public class SomeClass
    {
        public string StringProp { get; set; }
    }

    [DebuggerDisplay("The Value Is {Foo.StringProp}.")]
    public class SomeClass2
    {
        public SomeClass Foo { get; set; }
    }

    [DebuggerDisplay("The Value Is {Seven() - 6}.")]
    public class SomeClass3
    {
        public int Seven()
        {
            return 7;
        }
    }
}

现在测试(是的,这些都通过了):

using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace DebuggerDisplayStrings
{
    [TestClass]
    public class DebuggerDisplayReaderTests
    {
        [TestMethod]
        public void CanReadStringProperty()
        {
            var target = new SomeClass {StringProp = "Foo"};
            var reader = new DebuggerDisplayReader();
            Assert.AreEqual("The Value Is Foo.", reader.Read(target));
        }

        [TestMethod]
        public void CanReadPropertyOfProperty()
        {
            var target = new SomeClass2 {Foo = new SomeClass {StringProp = "Foo"}};
            var reader = new DebuggerDisplayReader();
            Assert.AreEqual("The Value Is Foo.", reader.Read(target));
        }

        [TestMethod]
        public void CanReadMethodResultAndDoMath()
        {
            var target = new SomeClass3();
            var reader = new DebuggerDisplayReader();
            Assert.AreEqual("The Value Is 1.", reader.Read(target));
        }
    }
}

最后是真货:

using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Text.RegularExpressions;
using Roslyn.Scripting.CSharp;

namespace DebuggerDisplayStrings
{
    public class DebuggerDisplayReader
    {
        // Get the fully evaluated string representation of the DebuggerDisplayAttribute's value.
        public string Read(object target)
        {
            var debuggerDisplayFormat = GetDebuggerDisplayFormat(target);
            if(string.IsNullOrWhiteSpace(debuggerDisplayFormat))
                return target.ToString();
            return EvaluateDebuggerDisplayFormat(debuggerDisplayFormat, target);
        }

        // Gets the string off the attribute on the target class, or returns null if attribute not found.
        private static string GetDebuggerDisplayFormat(object target)
        {
            var attributes = target.GetType().GetCustomAttributes(typeof(DebuggerDisplayAttribute), false);
            return attributes.Length > 0 ? ((DebuggerDisplayAttribute)attributes[0]).Value : null;
        }

        // Executes each bracketed portion of the format string using Roslyn,
        // and puts the resulting value back into the final output string.
        private string EvaluateDebuggerDisplayFormat(string format, object target)
        {
            var scriptingEngine = new ScriptEngine(new[] { GetType().Assembly });
            var formatInfo = ExtractFormatInfoFromFormatString(format);
            var replacements = new List<object>(formatInfo.FormatReplacements.Length);
            foreach (var codePart in formatInfo.FormatReplacements)
            {
                var result = scriptingEngine.Execute(codePart, target);
                replacements.Add((result ?? "").ToString());
            }
            return string.Format(formatInfo.FormatString, replacements.ToArray());
        }

        // Parse the format string from the attribute into its bracketed parts.
        // Prepares the string for string.Format() replacement.
        private static DebuggerDisplayFormatInfo ExtractFormatInfoFromFormatString(string format)
        {
            var result = new DebuggerDisplayFormatInfo();
            var regex = new Regex(@"\{(.*)\}");
            var matches = regex.Matches(format);
            result.FormatReplacements = new string[matches.Count];
            for (var i = matches.Count - 1; i >= 0; i-- )
            {
                var match = matches[i];
                result.FormatReplacements[i] = match.Groups[1].Value;
                format = format.Remove(match.Index + 1, match.Length - 2).Insert(match.Index+1, i.ToString(CultureInfo.InvariantCulture));
            }
            result.FormatString = format;
            return result;
        }
    }

    internal class DebuggerDisplayFormatInfo
    {
        public string FormatString { get; set; }
        public string[] FormatReplacements { get; set; }
    }
}

希望对您有所帮助。这只是大约一个半小时的工作,所以单元测试无论如何都没有完成,我敢肯定那里有错误,但它应该是一个可靠的开始,如果你对罗斯林方法。

于 2012-06-12T02:05:23.377 回答
2

我假设这是供您自己(团队)使用的。我没有亲自尝试过,但是您是否查看了有关如何自定义此处找到的 DebuggerDisplay 属性的说明?

于 2012-06-11T21:28:22.137 回答