确保目标继承一些自定义属性的接口
我需要创建一些自定义属性,用于我的反射函数。
正如我所看到的,这是用例:
- 用户创建一些类并用我的特殊属性(例如 [ImportantAttribute])标记它,
- 然后用户使用我的库中的函数执行某些操作。这些函数找到带有 [ImportantAttribute] 的类,并用它们做一些事情
主要问题是我的库中的函数期望,那些用 [ImportantAttribute] 标记的类继承我的接口(例如IMyInterface)
有没有办法让用户知道他是否用[ImportantAttribute]标记他的类并且在编译过程中忘记继承IMyInterface , 不是在运行时。通过某种方式指定该属性仅适用于继承IMyInterface的类。
与属性和字段的属性相同。
I need to create some custom attributes, to be used for my reflection functions.
Here is the usecase, as I see it:
- the user creates some class and marks it with my special attribute ([ImportantAttribute] for example)
- then the user does something with functions from my library. Those functions find classes with [ImportantAttribute] and do something with them
The main problem is that functions in my library expects, that classes wich was marked with [ImportantAttribute] inherit my interface (IMyInterface for example)
Is there any way to let user know if he mark his class with [ImportantAttribute] and forget to inherit IMyInterface during compilation, not in run time. Some way to specify that this attribute is only for classes that inherit IMyInterface.
Same with attributes for properties and fields.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
简单的回答:不,这是不可能的。不在编译时。您可以使用反射在运行时检查这一点。
在编译时使用属性(除了一些特殊的系统属性,例如
Obsolete
但它们直接合并到编译器中)可以做的最好的事情是使用[AttributeUsage]
属性。Simple answer: no, this is not possible. Not at compile-time. You can check this at runtime though using reflection.
The best you could do with attributes at compile-time (except some special system attributes such as
Obsolete
but which are directly incorporated into the compiler) is specify their usage with the[AttributeUsage]
attribute.我在我构建的几个框架中使用了您提到的策略,并取得了良好的成功。其中一个示例是向插件基础设施提供元数据:
这样做可以让我找出有关插件的信息,而无需实例化它们并读取元数据属性。
根据我的经验,我发现强制满足这两个要求的唯一方法是执行运行时检查并确保它是粗体和。在文档中。它远非最佳,但它是可以做到的最好的(我发现)。话又说回来,我确信有更好的方法来处理这个问题,但到目前为止,这对我来说非常可靠。
I've used the strategy you mention in a couple of the frameworks I've built with good success. One such example is for providing metadata to a plug-in infrastructure:
Doing so allows me to figure out information about plug-ins without having to instantiate them and read metadata properties.
In my experience in doing so, the only way I've found to enforce that both requirements are met is to perform runtime checks and make sure it is bold and <blink>blinking</blink> in the documentation. It is far from optimal but it is the best that can be done (that I've found). Then again I'm sure there is a better way to go about handling this but so far this has been pretty solid for me.