通过自定义属性生成附加代码
我对 C# 还很陌生,我有一个关于属性的问题。是否可以编写一个在编译时生成附加代码的自定义属性。例如:
[Forever]
public void MyMethod()
{
// Code
}
变为:
public void MyMethod()
{
while (true)
{
// Code
}
}
I am still fairly new to C# and I have a question regarding attributes. Is it possible to write a custom attribute which generates additional code at compile time. For example:
[Forever]
public void MyMethod()
{
// Code
}
Turns into:
public void MyMethod()
{
while (true)
{
// Code
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
开箱即用,不,这不是可以做到的事情。不过,使用 PostSharp 可以实现这一点:
http://www.sharpcrafters.com/aop。净/编译时编织
Out of the box, no, this isn't something that can be done. Using PostSharp though, this can be achieved:
http://www.sharpcrafters.com/aop.net/compiletime-weaving
Afterthought 的工作方式与 PostSharp 类似,通过对程序集执行编译时修改。在事后思考的情况下,您可以选择如何识别要进行的更改,通过查找已定义的属性、查找常见模式或简单地建立约定。
例如,我正在研究一个示例,使用 Afterthought 在编译时自动实现已编译程序集中 DbContext 公开的类型的实体框架接口。在本例中,我只是查找 DbContext 子类的任何类型,然后查看该类型的属性以确定要修改哪些 POCO 类型以与实体框架一起使用。
然而,像这样的程序集的编译时操作虽然功能强大,但对我来说仍然是最后的选择。 .NET 框架和 Microsoft 工具本身不支持它。尽管我编写 Afterthought 是为了支持需要这种间接级别的复杂情况,但我更喜欢尽可能使用标准的面向对象模式和内在的 C# 语言功能(例如委托)。最终,引入注入代码的自定义属性会在您的解决方案中引入一种特定于领域的语言,这将是审查您代码的人需要学习/理解的一件事,就像回答 SO 问题时一样;-)
Afterthought works similar to PostSharp by performing compile-time modifications to your assemblies. In the case of Afterthought you can choose how to identify the changes to make, either by looking for attributes you have defined, looking for common patterns, or simply establishing conventions.
For example, I am working on an example using Afterthought to automatically implement Entity Framework interfaces at compile-time for types exposed by a DbContext in a compiled assembly. In this case I am simply looking for any type that is a subclass of DbContext and then looking at the properties on this type to determine which POCO types to modify to work with Entity Framework.
However, compile-time manipulation of assemblies like this, while powerful, is still for me a choice of last resort. It is not natively supported by the .NET framework and Microsoft tools. Though I wrote Afterthought to support complex cases where this level of indirection was required, I prefer to use standard object-oriented patterns and intrinsic C# language features like delegates as much as possible. Ultimately, introducing custom attributes that inject code introduces a domain specific language into your solution, which will be one or thing to learn/understand for someone reviewing your code, like when answering an SO question ;-)