Let's say I have an interface IAppModule
, implemented by a few classes. Is it at all possible to write a custom attribute that can only be applied to types that expose IAppModule
? If so, how?
假设我有一个接口IAppModule,由几个类实现。是否可以编写一个只能应用于暴露IAppModule的类型的自定义属性?如果是这样,怎么样?
1 个解决方案
#1
8
No, unfortunately it's not possible.
不,不幸的是,这是不可能的。
You can, however, when using reflection to process your attributes, check if the decorated type is a class that implements the IAppModule interface.
但是,您可以在使用反射处理属性时检查修饰类型是否是实现IAppModule接口的类。
typeof(someType).GetInterfaces().Contains(typeof(IAppModule))
It doesn't stop users of your attribute from using it incorrectly (in any other class), but if you decide to go with this approach, I'd recommend providing very clear documentation describing how the attribute should be used and adding the layer of validation I mentioned above.
它不会阻止属性的用户错误地使用它(在任何其他类中),但如果您决定采用这种方法,我建议提供非常清晰的文档,描述如何使用该属性并添加验证我上面提到过。
#1
8
No, unfortunately it's not possible.
不,不幸的是,这是不可能的。
You can, however, when using reflection to process your attributes, check if the decorated type is a class that implements the IAppModule interface.
但是,您可以在使用反射处理属性时检查修饰类型是否是实现IAppModule接口的类。
typeof(someType).GetInterfaces().Contains(typeof(IAppModule))
It doesn't stop users of your attribute from using it incorrectly (in any other class), but if you decide to go with this approach, I'd recommend providing very clear documentation describing how the attribute should be used and adding the layer of validation I mentioned above.
它不会阻止属性的用户错误地使用它(在任何其他类中),但如果您决定采用这种方法,我建议提供非常清晰的文档,描述如何使用该属性并添加验证我上面提到过。