编译时间反射在C#反射、时间

2023-09-02 20:49:11 作者:爱ゞ已成傷

我经常写C#code,有使用魔法字符串来EX preSS属性名称。每个人都知道的问题与魔术字符串。他们是非常困难的重构,他们没有编译时检查,他们常常会导致难以诊断的问题。然而,C#/。NET使用它们的所有的地方的重新present属性/类/方法名。

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 have no compile time checking, and often they lead to hard-to-diagnose issues. Yet C#/.NET uses them all over the place to represent property/class/method names.

这个问题已经持续了一年又一年,唯一可行的解​​决方案是目前使用EX pression树,然后在运行时的属性名称解析。这让你满意的编译时检查,但它复杂化code(需要的类型防爆pression参数)的和的这样会导致一个运行时的成本。

This issue has persisted for years and years, and the only viable solution currently is to use an expression tree which is then parsed at run-time for the property name. This gets you satisfactory compile-time checking, but it complicates the code (requiring parameters of type Expression), and it incurs a run-time cost.

有谁知道,如果有曾经是一个功能考虑C#/。NET添加编译时反射来解决这个普遍的问题?

Does anyone know if there has ever been a feature consideration for C#/.NET to add compile-time reflection to overcome this pervasive problem?

看起来这将是一件容易除了使,这将是一个非重大更改,而且会大大有利于许多开发商。将typeof()运算符已进行编译时反射的一种形式,所以它看起来像一个运营商nameof()(或类似的东西)将是非常免费的。

It seems like it would be an easy addition to make, it would be a non-breaking change, and it would greatly benefit many developers. The typeof() operator already performs a form of compile-time reflection, so it seems like an operator nameof() (or something similar) would be very complimentary.

此外,没有人知道有这样的功能的任何潜在的问题?

In addition, does anyone know of any potential issues with such a feature?

感谢您的帮助。

推荐答案

的直接从源 - 这是一个用C#语言设计者一篇博客文章,以及在这个岗位网友问及同样的问题,你和在回答。笔者认为将有必要指定你要问的每一个元数据项的语法,这不是微不足道的 - 即。其中超载你想要的,如果你想信息的方法,该方法是重载?如果有泛型和显式接口实现参与?等等。事实证明,由于这些原因,而这是不被视为值得推行的2009年,我们将获得在C#6,2015年 - 看的 C#语言设计说明2014年7月9日。

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 .