生成自定义编译时警告C#

时间:2009-09-14 07:32:50

标签: c# compiler-construction custom-attributes postsharp

我正在使用VS2008,并希望根据属性上的自定义属性创建编译时警告/错误(如果可能的话)。

目前有两个案例让我感兴趣:

  [MyAttribute (typeof(MyClass)]

MyClass必须实现一个接口。目前我在属性的构造函数中声明了这一点,但是由于堆栈跟踪的性质,这不容易跟踪:

 public MyAttribute (Type MyClassType)
    {
         System.Diagnostics.Debug.Assert(typeof(MyInterface).IsAssignableFrom(MyClassType),
                                         "Editor must implement interface: " + typeof(MyInterface).Name);

    }

我感兴趣的第二种情况是我在属性中定义了一个类型,如果该类型实现了一个接口,那么如果另一个属性不存在则应该显示警告。

即。 if(MyClass.Implements(SomeInterface)&&!Exists(SomeAttibute)){Generate Warning}

[MyAttribute(typeof(MyClass)] 
// Comment next line to generate warning
[Foo ("Bar")]

谢谢!

1 个答案:

答案 0 :(得分:7)

您可以使用PostSharp执行此操作。

我曾经做过,并解释了如何做here

相关问题