使用反射访问属性

 using System;
using System.Collections.Generic;
using System.Text;

namespace 使用反射访问属性
{
    [System.AttributeUsage(System.AttributeTargets.Class |
                        System.AttributeTargets.Struct,
                        AllowMultiple = true) 
 ]
    public class Author : System.Attribute
    {
        string name;
        public double heyu;
        public double version;
        //这里定义多少个变量,对应使用的地方都可以填
      
        public Author(string name)
        {
            this.name = name;
            version = 1.0;  // Default value
            heyu = 1;
        }

        public string GetName()
        {
            return name;
        }
    }


}

 

 

using System;
using System.Collections.Generic;
using System.Text;

namespace 使用反射访问属性
{
    [Author("H. FirstClass")]
    public class FirstClass
    {
        // ...
    }

    // No Author attribute
    public class SecondClass
    {
        // ...
    }

   // [Author("H. ThirdClass"), Author("M. Knott", heyu = 1, version = 2.0)]
    //以上等效于下面
    [Author("H. ThirdClass")]
    [Author("M. Knott", heyu = 1, version = 2.0)]
    public class ThirdClass
    {
        // ...
    }


}

using System;
using System.Windows.Forms;

namespace 使用反射访问属性
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            PrintAuthorInfo(typeof(FirstClass));
            PrintAuthorInfo(typeof(SecondClass));
            PrintAuthorInfo(typeof(ThirdClass));

        }

        private static void PrintAuthorInfo(System.Type t)
        {
            System.Console.WriteLine("Author information for {0}", t);
            System.Attribute[] attrs = System.Attribute.GetCustomAttributes(t);  // reflection

            foreach (System.Attribute attr in attrs)
            {
                if (attr is Author)
                {
                    Author a = (Author)attr;
                   // System.Console.WriteLine("   {0}, version {1:f}", a.GetName(), a.version);
                    MessageBox.Show(a.GetName().ToString() + a.version.ToString());
                }
            }
        }

    }
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值