C# Attributes(特性)

本文介绍了如何使用C#中的反射API读取类的属性和元数据,包括使用Attribute来标记类成员并获取其相关信息。通过实例展示了方法一和方法二的不同应用方式。

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

特性Attributes

using System;
using System.Reflection;

namespace Con_Attribute
{
    class Program
    {
        static void Main(string[] args)
        {
            //方法一:使用反射来读取 Attribute
          //  Student student = new Student();
           // System.Reflection.MemberInfo info = typeof(Student); //通过反射得到student类的信息
            //Hobby hobbyattr = (Hobby)Attribute.GetCustomAttributes(info)[0];
            //Hobby hobbyattr = (Hobby)Attribute.[0];

            //方法二:使用反射来读取 Attribute
             Student instence = new Student();
             Type type = instence.GetType();            
            // PropertyInfo[] vv = type.GetProperties();
             // PropertyInfo[] vv = typeof(Student).GetProperties();不需要实例化,可以直接进行寻找
             MemberInfo vv = type.GetField("profession");//字段
            var gg= vv.GetCustomAttributes(false);
            //if (hobbyAttr != null)
            //{
            //    Console.WriteLine("类名:{0}",type.Name);
            //    //Console.WriteLine("类名:{0}", info.Name);
            //    Console.WriteLine("兴趣类型:{0}", hobbyAttr.Type);
            //    Console.WriteLine("兴趣指数:{0}", hobbyAttr.Level);
            //}
        }
    }


    //注意:"Sports"是给构造函数的赋值,Level = 5 是给属性的赋值。
     //[Hobby("Sports", Level = 5)] 
    class Student
    {
        [Hobby("Football", Level = 10)]
        public string profession;

        
        public string Profession
        {
            get { return profession; }
            set { profession = value; }
        }
    }


    //建议取名:HobbyAttribute
   // [AttributeUsage(AttributeTargets.Field )]
    class Hobby : Attribute // 必须以System.Attribute 类为基类
    {
        // 参数值为null的string是危险的,所以必需在构造函数中赋值
        public Hobby(string _type) // 定位参数
        {
            this.type = _type;
        }

        //兴趣类型
        private string type;
        public string Type
        {
            get { return type; }
            set { type = value; }
        }

        //兴趣指数
        private int level;
        public int Level
        {
            get { return level; }
            set { level = value; }
        }
    }
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值