c# - 根据类属性引发警告

标签 c# reflection attributes

这是一些代码:

class Program
{
    static void Main(string[] args)
    {
        MyClass class1 = new MyClass();
        MyOtherClass class2 = new MyOtherClass();

        Helper.UseAttribute<MyClass>(class1);

        //Raise a warning to tell the developer that they cannot use this class
        //as there is no property with the specified attribute.
        Helper.UseAttribute<MyOtherClass>(class2);
    }
}

public class MyAttribute : System.Attribute { }

class MyClass
{
    [MyAttribute]
    public string SomethingAwesome { get; set; }
}

class MyOtherClass
{
    public string SomethingElseWhichIsAlsoPrettyAwesome { get; set; }
}

static class Helper
{
    public static void UseAttribute<T>(T sender)
    {
        //Do something with the property that has MyAttribute
        //If there isn't a property with this attribute, then raise
        //a warning.
    }
}

在理想情况下,我想限制开发人员将类传递给不具有特定属性的方法。

我知道我可以使用一个接口(interface),或一些描述的基类,但真正的问题是是否有可能像上面的例子那样。

最佳答案

如果您愿意使用 VS 2015 预览版或等到 VS 2015 发布,您可以使用 Roslyn为此。

你会写一个 DiagnosticAnalyzer类,可能会注册一个语法节点分析器来专门查找对 Helper.UseAttribute<T> 的调用.当您找到这样的用途时,您会找到 T 的符号并检查 MyAttribute 是否有任何属性应用于它的属性,如果没有则发出警告。此警告将显示在 Visual Studio 本身中,并应用于 CI 构建(假设您适本地注册了分析器程序集)。

开始使用 Roslyn 诊断 API 需要一段时间,但一旦您习惯了它,它就会真的非常强大。

当然,另一种选择是在执行时抛出异常,并依赖于所有调用者周围的单元测试,以便您能够在它们失败时捕获它:)您可能应该这样做以及通过 Roslyn 添加编译时支持。

关于c# - 根据类属性引发警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27904912/

相关文章:

c# - 检查是否为任何属性分配了值

javascript - 通过 Javascript 将属性添加到现有 div 标签

jquery - 在 IE 中使用 jQuery 获取属性

c# - 避免在 C# 中重复订阅事件

c# - Ajax 请求后 .NET 后端的奇怪响应

c# - 我该如何设置(最小起订量设置)

c# - 编译基于 C# 的 Windows (WinForms App) 应用程序以在 Mac OS High Sierra 或 Mojave 上运行

java - 使用泛型概括不同的实现

Java 8、流过滤器、反射、NoSuchMethodException

jquery - 使用 jQuery 替换链接中的部分 HREF 属性