特定类的 C# AttributeUsage
是否可以使用 AttributeUsage 之类的东西将属性的使用限制为特定类(不仅仅是 AttributeTargets.Class - 可以是任何类)?
Is it possible to have something like AttributeUsage to restrict the use of an attribute to a specific class (not just AttributeTargets.Class - that would be any class)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您有权访问特定类,则完成此操作的一种方法由 Marc Gravel 详细介绍:http://marcgravell.blogspot.com/2009/06/restricting-attribute-usage.html。基本上,您将属性实现为特定类型的受保护类。那么它只能被该类型使用。
One way to accomplish this, if you have access to the specific class, is detailed by Marc Gravel here: http://marcgravell.blogspot.com/2009/06/restricting-attribute-usage.html. Basically you implement the attribute as a protected class of the specific type. Then it can only be used by that type.
不。框架中没有任何东西可以做到这一点。
但是,使用相关属性的代码始终可以进行检查,以确保该类的类型是特定的类(或其子类之一)。
属性本身不执行任何操作 - 因此这应该具有相同的效果。
No. There is nothing in the framework that would do this.
However, the code that uses the attribute in question could always check to make sure that the class's type is the specific class (or one of its subclasses).
Attributes, by themselves, do nothing - so this should have the same effect.
使属性中的所有数据只能通过公共静态方法访问,该方法采用您想要的类并检查它是否具有给定的属性。
Make all data in the Attribute accessible only by a public static method which takes the class you want in question and checks to see if it has the given attribute.