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

本文介绍了.NET框架中的特性(Attribute),包括其定义、用途及如何在程序中应用。特性分为预定义特性和自定义特性,文章提供了具体的代码示例,帮助读者理解如何创建和使用特性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

特性(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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值