C#高级 04特性

本文介绍了特性在编程中的概念,它是.NET中用于添加程序结构元数据的语言结构。作者详细讲解了如何声明自定义特性,如继承自System.Attribute并提供属性值,以及如何在类中应用和获取这些特性信息。

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

1.什么是特性

特性是一种允许我们向程序的程序集增加元数据的语言结构。他是用于保存程序结构信息的某种特殊类型的类。
  • 设计用来获取和使用元数据的程序(对象浏览器)叫做特性的消费者
  • .NET预定了很多特性,我们也可以声明自定义特性
  • 将应用了特性的程序结构叫做目标

2.声明自定义特性

声明一个特性类和声明其他特性类一样,有下面的注意事项

  • 声明一个派生自System.Attribute的类
  • 给他起一个以后缀Attribute结尾的名字
    例如定义一个特性类
	[AttributeUsage(AttributeTargets.Class)]  //特性:定义使用目标 --> class
    internal sealed class InformationAttribute:Attribute
    {
        public string developer;
        public string version;
        public string desciption;

        public InformationAttribute(string developer, string version, string desciption)
        {
            this.developer = developer;
            this.version = version;
            this.desciption = desciption;
        }
    }

在另一个类的函数下使用特性

[Information("sino","v1.1","发射核弹")]
internal class Program
    {
        static void Main(string[] args)
        {
            Type t = typeof(Program);
            //打印特性信息
            bool result = t.IsDefined(typeof(InformationAttribute), false);
            Console.WriteLine(result);
            object[] attributeArray = t.GetCustomAttributes(false);

            Console.ReadKey();
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值