c# - 生成自定义编译时警告 C#

标签 c# compiler-construction custom-attributes postsharp

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

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

[MyAttribute (typeof(MyClass)]

MyClass 必须实现一个接口(interface)。目前我在属性的构造函数中声明了这一点,但是由于堆栈跟踪的性质,这并不容易追踪:

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

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

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

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

谢谢!

最佳答案

你可以用 PostSharp 做到这一点.

我做过一次,并解释了如何做 here

关于c# - 生成自定义编译时警告 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1420143/

相关文章:

c# - Android 上的 .NET 框架

c# - 为 RequiredAttribute 提供自定义消息

c# - 如何从 C# 中的子类型树获取属性的声明类型

jQuery - 循环遍历具有特定属性的元素

c++ - 编译器怎么会认为这个变量不是常量?

c - c程序中链接的隐藏例程

c# - 命令事件不会触发动态创建的控件的 asp.net

C# ASP.net 测试用户是否来自本地网络

c# - 比较字符串和 int 时,将它们都转换为字符串与将它们都转换为 int 有什么区别?

optimization - 在 Erlang 中是否优化了别名函数