19

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

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

  [MyAttribute (typeof(MyClass)]

MyClass 必须实现接口的地方。目前我在属性的构造函数中断言这个,但是由于堆栈跟踪的性质,这并不容易追踪:

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

    }

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

IE if (MyClass.Implements(SomeInterface) && !Exists(SomeAttibute)) { 生成警告}

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

谢谢!

4

1 回答 1

6

你可以用PostSharp做到这一点。

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

于 2009-09-14T07:39:15.337 回答