【问题标题】:Generating a custom compile time warning C#生成自定义编译时警告 C#
【发布时间】:2010-11-28 01:18:57
【问题描述】:

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

目前我感兴趣的有两种情况:

  [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. if (MyClass.Implements(SomeInterface) && !Exists(SomeAttibute)) { 生成警告 }

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

谢谢!

【问题讨论】:

标签: c# compiler-construction custom-attributes postsharp


【解决方案1】:

您可以通过 PostSharp 做到这一点。

我曾经做过,并解释了如何做here

【讨论】:

  • 非常感谢!我之前看过post sharp(对于另一个问题)并决定反对它,但现在我想我会重新评估;)
  • 我刚刚发现了一个问题——当它派生自 PostSharp.Laos.OnMethodInvocationAspect 而不是 System.Attribute 时,似乎 GetCustomAttributes() 不再返回该属性
  • 你的意思是它返回 System.Attribute ?你不能把它转换成你自己的属性吗? (GetCustomAttributes 总是返回一个 System.Attribute AFAIK 数组,所以我认为你总是必须强制转换?
  • 不,PostShap 在编译后阶段将 Aspect 属性从元数据中剔除(ILDSAM 证实了这一点)。我确实通过使用 CompoundAspect 而不是 OnMethodInvocationAspect 作为基类来解决它。然后覆盖 ProvideAspects 将自身重新插入到元数据中。 -呼-。再次感谢:)
  • 我刚刚发现使用 '[MulticastAttributeUsage(MulticastTargets.Property, PersistMetaData = true)]' 消除了对 CompoundAspect 的需要。
猜你喜欢
  • 2014-04-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-09
  • 2020-05-15
  • 1970-01-01
相关资源
最近更新 更多