使用自定义属性最简单最优雅的方法是什么 [英] What's the simplest most elegant way to utilize a custom attribute

查看:21
本文介绍了使用自定义属性最简单最优雅的方法是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以有点忏悔,我从来没有写过属性类.我知道它们的目的是用标志或额外的功能装饰类.

So a little confession, I've never written an attribute class. I understand they serve the purpose of decorating classes with flags or extra functionality possibly.

谁能给我一个简单的例子,不仅可以创建属性并将其应用到类,还可以利用另一个代码块中的属性.我见过的唯一使用任何形式属性的代码示例是通过反射来实现的,尽管我一直希望有一种方法可以在没有反射的情况下使用它们.

Can someone give me a quick example of not just creating and applying an attribute to a class, but rather utilizing the attribute from another block of code. The only code samples I've ever seen to utilize any form of attributes was doing so with reflection, though I've always hoped there's a way of using them without reflection.

推荐答案

属性总是与反射一起使用.它们在编译期间被烘焙到类型的元数据中,读取它们的唯一方法是通过反射.当你想写一个类型并且你想将一些元数据与它相关联时使用属性,这些元数据可以被这种类型的消费者使用.

Attributes are always used with reflection. They are baked into the metadata of the types during compile time and the only way to read them is through reflection. Attributes are used when you want write a type and you want to associate some metadata with it which could be used by consumers of this type.

这篇关于使用自定义属性最简单最优雅的方法是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆