AttributeUsage(AttributeTargets.Property) - 有没有办法为属性类型指定黑/白名单?
我有一个定义为 System.AttributeUsage(AttributeTargets.Property) 的自定义属性。 当开发人员将属性添加到不是类的属性时,我希望编译器抛出编译错误。有什么办法可以做到这一点吗?
I have a custom attribute defined as System.AttributeUsage(AttributeTargets.Property).
I want the compiler to throw a compile error when a developer adds the attribute to a property that is a NOT a Class. Is there any way to do that ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不,没有类似的东西可用。
但是,如果您在自己的代码中担心这一点,我建议您编写一些测试来遍历所有程序集中所有类型的所有属性,并检查该属性是否已正确应用。
在可行的情况下,编译时检查是最好的,但通过测试进行验证总比没有好:)
No, there's nothing like that available.
However, if you're concerned about this within your own code, I suggest you write some tests which go through all the properties in all the types in all your assemblies, and check that the attribute has been applied appropriately.
Compile-time checking is best when it's feasible, but validating with tests is better than nothing :)
不要抱太大希望,但您也许可以使用 Microsoft 的代码合约或 FxCop 之类的工具强制出现自定义编译器错误:
代码合约:
http://msdn.microsoft.com/en-us/devlabs/dd491992.aspx
FxCop:
http://msdn.microsoft.com/en- us/library/bb429476(v=vs.80).aspx
您还可以查看 Spec#:
http://research.microsoft.com/en-us/projects/specsharp/
Don't get your hopes up, but you might be able to force a custom compiler error using something like Microsoft's Code Contracts or FxCop:
Code Contracts:
http://msdn.microsoft.com/en-us/devlabs/dd491992.aspx
FxCop:
http://msdn.microsoft.com/en-us/library/bb429476(v=vs.80).aspx
You might also take a look at Spec#:
http://research.microsoft.com/en-us/projects/specsharp/