【问题标题】:Can an attribute require inheritance or implementation of a class or interface?属性可以要求继承或实现类或接口吗?
【发布时间】:2019-10-05 18:08:12
【问题描述】:

尝试将System.AttributeUsage 属性应用于类时,Visual Studio 将显示错误"Attribute 'AttributeUsage' is only valid on classes derived from System.Attribute"。是否可以为自定义属性指定这样的要求?

想象一个属性类CommandAttribute,它将指定命令的名称。它应该只出现在实现ICommand 的类上,这样我们就可以保证类上存在ExecuteCommand(...) 之类的方法。

我当然可以使用反射来检查应用的类在运行时是否实现了接口,但理想情况下我们可以在编译时强制执行。

【问题讨论】:

    标签: c# .net reflection custom-attributes system.reflection


    【解决方案1】:

    很遗憾,C# 语言不直接支持这一点。

    但是,您可以使用 .NET 编译器平台(又名 Roslyn)编写 your own code analysis rule 并自己强制执行该条件。

    【讨论】:

      猜你喜欢
      • 2012-03-09
      • 2010-10-07
      • 1970-01-01
      • 2011-03-31
      • 1970-01-01
      • 2015-12-23
      • 2015-11-24
      • 1970-01-01
      • 2012-05-29
      相关资源
      最近更新 更多