属性是否需要继承或实现 class 或接口?

Can an attribute require inheritance or implementation of a class or interface?

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

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

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

遗憾的是,C# 语言不直接支持此功能。

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