C#特性示例

本文详细介绍了C#中的自定义特性、查看特性和条件特性的使用,通过示例代码展示了如何应用这些特性,同时涵盖了过时特性的处理方式,帮助开发者更好地理解和运用C#的特性。
摘要由CSDN通过智能技术生成

自定义特性

示例代码:

using System;

namespace Custom
{
   
    class Program
    {
   
        static void Main(string[] args)
        {
   
            Type type = typeof(Person);
            Object[] array = type.GetCustomAttributes(false);
            TestAttribute test = array[0] as TestAttribute;
            Console.WriteLine(test.Id);
            Console.WriteLine(test.Description);
            Console.WriteLine(test.Version);
        }
    }

    //1.自定义特性类必需以Attribute结尾
    //2.需要继承自Attribute
    //3.一般自定义特性类中不定义方法
    //4.自定义的特性需要用AttributeUsage指明该特性的适用程序结构
    [AttributeUsage(AttributeTargets.Class)]    //表示该自定义特性用于Class这种类型
    class TestAttribute : Attribute
    {
   
        //构造方法
        public TestAttribute(int Id, string Description, string Version)
        {
   
            this.Id = Id;
            this.Description = Description;
            this.Version = Version;
        }

        public int Id;
        public string Description;
        public string Version;
    }

    [Test(1, "自定义特性", "1.0.0")
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值