Generating a custom compile time warning C#

2020-02-02 19:14发布

问题:

I'm using VS2008 and would like to create a compile time warning / error based on custom attributes on a property (if it is possible).

There are two cases which interest me currently:

  [MyAttribute (typeof(MyClass)]

Where MyClass has to implement an interface. Currently I assert this in the constructor of the attribute, however this doesn't make it easy to track down, due to the nature of the stack trace:

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

    }

The second case which interests me is where I have a type defined in an attribute, if that type implements an interface, then a warning should be displayed if another attribute isn't present.

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

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

Thanks!

回答1:

You can do that with PostSharp.

I've once done it, and explained how to do it here