任何复制DebuggerDisplayAttribute如何生成结果字符串的代码?

时间:2012-06-08 02:08:24

标签: .net custom-attributes

任何人都知道任何复制DebuggerDisplayAttribute如何解析和收集结果字符串的代码?

我想创建一个自定义属性来完成几乎所有的事情。类似于“当遇到断点时...”,您可以在花括号中使用变量,如“{variable}”。

我已经处理过简单的情况,例如“{Name}”,但像“{Foo.Name}”这样的东西需要我需要帮助的额外反射代码。

基本上,我想使用DebuggerDisplayAttribute文档中定义的规则解析字符串。目前,我可以解析并解决“我是{GetName()}”。我需要帮助“Foo的名字:{Foo.Name}”

2 个答案:

答案 0 :(得分:5)

希望这段代码完全合适......我使用Microsoft Roslyn及其C#Scripting功能将属性值中的“代码”作为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; }
    }
}

希望能帮到你。它只有大约一个半小时的工作,所以单元测试无论如何都不完整,而且我确定那里有bug,但是如果你对它有好处,它应该是一个坚实的开端。罗斯林的方法。

答案 1 :(得分:2)

我假设这是为了你自己(团队)的使用。我个人没试过这个,但你看过如何自定义DebuggerDisplay属性的解释here