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

Cou*_*y D 19 c# compiler-construction postsharp custom-attributes

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

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

  [MyAttribute (typeof(MyClass)]
Run Code Online (Sandbox Code Playgroud)

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

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

    }
Run Code Online (Sandbox Code Playgroud)

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

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

[MyAttribute(typeof(MyClass)] 
// Comment next line to generate warning
[Foo ("Bar")]
Run Code Online (Sandbox Code Playgroud)

谢谢!

Fre*_*els 7

你可以用PostSharp做到这一点.

我曾经做过,并在这里解释了如何做到这一点