【发布时间】: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