通过自定义属性产生额外的code自定义、属性、code

2023-09-06 14:18:08 作者:粉嘟嘟的小猪

我还是相当新的C#和我有一个关于属性的问题。是否有可能写入产生额外的code在编译时的自定义属性。例如:

  [永恒]
公共无效的MyMethod()
{
    // code
}
 

打开到:

 公共无效的MyMethod()
{
    而(真)
    {
        // code
    }
}
 

解决方案

开箱即用,不,这不是一朝一夕所能完成的。使用PostSharp不过,这是可以实现的:

自定义属性的应用

http://www.sharpcrafters.com/aop.net/compiletime-weaving

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
    }
}

解决方案

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