问题描述
我真的不太了解 C# 中的一般属性,我已经看到它们以许多不同的方式/地方使用,但我认为我没有看到其中一些的重要性.有些肯定很重要,因为它们提供了一个引人注目的功能,例如 [Serializable]
.然而,其他的似乎并不那么重要,例如我的同事用 [DataMember]
标记属性的一个.
I really don't know much about attributes in general in C#, I've seen them in use in a lot of different ways/places but I don't think I see the importance of some of them. Some definitely have importance because they provide a noticeable function, such as [Serializable]
. Yet, others don't seem so important, such as one my coworker uses to mark properties with [DataMember]
.
我想我的问题是,什么是属性,它们有什么用处?有没有办法创建我自己的属性,我如何判断字段/方法/类/是否具有特定属性或在这些属性中设置了哪些值?
I suppose my question is, what are attributes and how are they useful? Is there a way to create my own attributes and how can I tell if fields/methods/classes/whatever have particular attributes or what values are set in those attributes?
推荐答案
什么是属性?
属性使您能够在描述该类型或方法的元数据中嵌入有关类型或方法的信息.
Attributes enable you to embed information about a type or method in the metadata which describes that type or method.
您通常希望使用属性描述关于类型或方法的机制的事实,而不是类型或方法的含义.例如,假设您有一个类型Employee.关于Employee的含义的一个事实是它是一种Person,一个Employee有一个Manager,等等.关于Employee 的机制 的一个事实是,它可以是数据绑定的目标,也可以序列化到磁盘,或其他任何东西.一个员工不能被序列化到磁盘,但是class Employee 可以.属性可让您将有关技术细节的信息与语义模型分开.
You typically want to use attributes to describe facts about the mechanism of the type or method rather than the meaning of the type or method. For example, suppose you have a type Employee. A fact about the meaning of Employee is that it is a kind of Person, that an Employee has a Manager, and so on. A fact about the mechanism of Employee is that it can be the target of data binding, or it can be serialized to disk, or whatever. An employee cannot be serialized to disk, but the class Employee can be. Attributes let you separate information about the technical details from the semantic model.
有没有办法创建我自己的属性?
Is there a way to create my own attributes?
是的.创建一个扩展属性的类.按照惯例,您希望将其命名为FooAttribute".如果这样做,您可以自行决定使用 [Foo] 语法或 [FooAttribute] 语法.
Yes. Create a class which extends Attribute. By convention you want to name it "FooAttribute". If you do so you can use either the [Foo] syntax or the [FooAttribute] syntax at your discretion.
我如何判断字段/方法/类/任何东西是否具有特定属性或在这些属性中设置了哪些值?
How can I tell if fields/methods/classes/whatever have particular attributes or what values are set in those attributes?
对反射对象使用 GetCustomAttributes 方法.
Use the GetCustomAttributes method on the reflection objects.
我应该在哪里阅读以获取更多信息?
Where should I read for more information?
从属性教程开始:
http://msdn.microsoft.com/en-us/library/aa288454(VS.71).aspx
然后阅读 C# 规范的第 17 章.
And then read all of chapter 17 of the C# specification.
这篇关于C# 属性及其用途的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!