Generating a custom compile time warning C#

末鹿安然 提交于 2019-11-27 01:20:47

问题


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



来源:https://stackoverflow.com/questions/1420143/generating-a-custom-compile-time-warning-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!