Compile Time Reflection in C#

前端 未结 4 780
鱼传尺愫
鱼传尺愫 2020-12-13 09:55

I frequently write C# code that has to use magic strings to express property names. Everyone knows the problems with magic strings. They are very difficult to refactor, they

相关标签:
4条回答
  • 2020-12-13 10:37

    Straight from the source - this is a blog post by a C# language designer, and the "User" in this post asks about the same questions as you and is answered. The author says there would be a need to specify a syntax for every metadata item you'd want to ask for and it's not trivial - ie. which overload you want, if you want "info-of" method and the method is overloaded? What if there are generics and explicit interface implementations involved? And so on. It turns out, while it wasn't deemed worthy of implementation in 2009 because of those reasons, we will get it in C# 6 in 2015 - see C# Language Design Notes for Jul 9, 2014 .

    0 讨论(0)
  • 2020-12-13 10:40

    I was having a similar problem. Only recently discovered that .NET Framework 4.5 has a feature called the Caller Info attributes. By using these, you can obtain information about the caller to a method at compile time. You can obtain file path of the source code, the line number in the source code, and the member name of the caller.

    public void DoProcessing()
    {
        TraceMessage("Something happened.");
    }
    
    public void TraceMessage(string message,
            [CallerMemberName] string memberName = "",
            [CallerFilePath] string sourceFilePath = "",
            [CallerLineNumber] int sourceLineNumber = 0)
    {
        Trace.WriteLine("message: " + message);
        Trace.WriteLine("member name: " + memberName);
        Trace.WriteLine("source file path: " + sourceFilePath);
        Trace.WriteLine("source line number: " + sourceLineNumber);
    }
    
    0 讨论(0)
  • 2020-12-13 10:44

    In C# 6.0, a new operator, nameof, is being added that will allow you to get the names of properties, classes, fields, events, and variables at compile time.

    Link to the design notes

    No more reflection for information the compiler already knows at design time!

    0 讨论(0)
  • 2020-12-13 10:44

    Yet C#/.NET uses them all over the place to represent property/class/method names.

    First off: I disagree. There are certain frameworks (WebForms, e.g.) that use magic strings all over the place, but the base libraries for C# and .NET tend to avoid such things remarkably well.

    Secondly: In many instances where magic strings are used, ReSharper is able to recognize errors. This can help quite a bit.

    Finally: What you're asking for may be possible via the Roslyn Compiler, which promises to provide "Compiling as a service."

    0 讨论(0)
提交回复
热议问题