gpt4 book ai didi

C# 属性及其用途

转载 作者:可可西里 更新时间:2023-11-01 03:05:54 25 4
gpt4 key购买 nike

我真的不太了解 C# 中的一般属性,我已经看到它们以很多不同的方式/地方使用,但我认为我没有看到其中一些的重要性。有些肯定很重要,因为它们提供了引人注目的功能,例如 [Serializable]。然而,其他的似乎并不那么重要,例如我的同事使用 [DataMember] 标记属性。

我想我的问题是,什么是属性,它们有什么用?有没有办法创建我自己的属性,我如何判断字段/方法/类/任何具有特定属性或在这些属性中设置了哪些值?

最佳答案

what are attributes?

属性使您能够将有关类型或方法的信息嵌入到描述该类型或方法的元数据中。

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.例如,假设您有一个类型 Employee。关于 Employee 的含义的一个事实是它是一种人,一个 Employee 有一个 Manager,等等。关于 Employee 的机制 的一个事实是,它可以是数据绑定(bind)的目标,也可以序列化到磁盘,等等。员工无法序列化到磁盘,但 Employee 可以。属性让您可以将有关技术细节的信息与语义模型分开。

Is there a way to create my own attributes?

是的。创建一个扩展属性的类。按照惯例,您要将其命名为“FooAttribute”。如果这样做,您可以自行决定使用 [Foo] 语法或 [FooAttribute] 语法。

How can I tell if fields/methods/classes/whatever have particular attributes or what values are set in those attributes?

对反射对象使用 GetCustomAttributes 方法。

Where should I read for more information?

从属性教程开始:

http://msdn.microsoft.com/en-us/library/aa288454(VS.71).aspx

然后通读 C# 规范的第 17 章。

关于C# 属性及其用途,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3197265/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com