六、C#学习基础篇---特性

特性(Attribute)是用于在运行时传递程序中各种元素(比如类、方法、结构、枚举、组件等)的行为信息的声明性标签。您可以通过使用特性向程序添加声明性信息。一个声明性标签是通过放置在它所应用的元素前面的方括号([ ])来描述的。

特性(Attribute)用于添加元数据,如编译器指令和注释、描述、方法、类等其他信息。.Net 框架提供了两种类型的特性:预定义特性和自定义特性。

所有特性类都派生自标准库提供的 Attribute 基类。 特性的应用方式为,在相关声明前的方括号内指定特性的名称以及任意自变量。 如果特性的名称以 Attribute 结尾,那么可以在引用特性时省略这部分名称

特性的语法
[attribute(positional_parameters, name_parameter = value, …)]

预定义特性
Net 框架提供了三种预定义特性:

AttributeUsage
Conditional
Obsolete

在unity更新之后就可以看到很多api不能用了,要嘛用新的代替,要嘛直接废弃了,以下是unity(Component)一个简单的例子
示例:
//
// 摘要:
// ///
// The Rigidbody attached to this GameObject. (Null if there is none attached).
// ///
[Obsolete(“Property rigidbody has been deprecated. Use GetComponent() instead. (UnityUpgradable)”, true)]
public Component rigidbody { get; }

以下是一个自定义特性:
[System.AttributeUsage(System.AttributeTargets.Class |
System.AttributeTargets.Struct)
]
public class Author : System.Attribute
{
private string name;
public double Version;

public Author(string name)
{
    this.name = name;
    Version = 1.0;
}

}

[Author(“小数点”, Version = 1.1)]
class Person
{

}

官方文档:https://docs.microsoft.com/zh-cn/dotnet/csharp/tour-of-csharp/attributes

猜你喜欢

转载自blog.csdn.net/u011017980/article/details/79423796