2009-09-14 41 views
18

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

有两种情况,其利息我目前:

[MyAttribute (typeof(MyClass)] 

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

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

    } 

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

I.E.如果(MyClass.Implements(SomeInterface)& &!是否存在(SomeAttibute)){生成警告}

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

谢谢!

+0

有趣的问题,我很好奇,如果这样的事情是可能的。 +1 – 2009-09-14 07:38:49

+0

也有兴趣。 – 2010-03-04 00:01:56

+0

http://stackoverflow.com/questions/154109/custom-compiler-warnings – 2013-08-16 04:07:00

回答

7

您可以使用PostSharp来做到这一点。

我已经做过一次,并解释如何做到这一点here

+0

非常感谢!我之前曾仔细看过帖子(针对另一个问题)并决定采取反对措施,但现在我认为我会重新评估;) – 2009-09-15 01:11:27

+0

我刚刚发现了一个问题 - 看起来GetCustomAttributes()不再返回当它派生自PostSharp.Laos.OnMethodInvocationAspect而不是System.Attribute时的属性 – 2009-09-15 02:56:14

+0

你的意思是它返回System.Attribute?你不能把它转换成你自己的属性吗? (GetCustomAttributes总是返回一个System.Attribute AFAIK的数组,所以你总是必须施放我的想法? – 2009-09-15 06:57:45