.net的反射与属性

搞了一天,TMD在网上搜了一天,没有一个具体的总结。现在将我总结反射与属性的应用分享给我的朋友.......

什么是属性(不是字段什么年龄,性别这些)?

举个列子如下图:

.net的反射与属性_第1张图片

看backcolor是属性名字,再看最下面是:组件的背颜色。就是该属性的描述了

再看他们是如何实现的(下图):

.net的反射与属性_第2张图片

两个大括号就是了.......那你会想这个效果是怎么实现的呢?你就接着往下看...

首先自定义属性:代码如下(这是一个类库即Dll文件)

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

namespace CustomAttribute
{
    [System.AttributeUsage(AttributeTargets.All, AllowMultiple = true)]
    public class Name:Attribute
    {
        string name;
        public string Name1
        {
            get { return name; }
            set { name = value; }
        }
        public Name(string name)
        {
            this.name = name;
        }
    }
}

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

namespace CustomAttribute
{
    [System.AttributeUsage(AttributeTargets.All, AllowMultiple = true)]
    public class Description:Attribute
    {
        string Desc;
        public string Desc1
        {
            get { return Desc; }
            set { Desc = value; }
        }
        public Description(string Description)
        {
            this.Desc = Description;
        }
    }
}

一定要继承attribute这个类,这样你才实现属性效果,这么一句话

    [System.AttributeUsage(AttributeTargets.All, AllowMultiple = true)]
告诉大家这个属性在什么地方能用呢?这里的AttributeTargets是个menu类型的,all表示适应所有,有类,方法,接口等,你可能不能我怎么用啊?再往下看。。。

自定义属性的应用:

在定义一个类库(把属性加进去):(记住再添加的时候要把上面的类库生成的Dll要添加应用)

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

namespace ClassLibrary1
{
    public class Class1
    {
        [CustomAttribute.Name("加法")]
        [CustomAttribute.Description("加法运算")]
        public int add(int a, int b)
        {
            return a + b;
        }
        [CustomAttribute.Name("减法")]
        [CustomAttribute.Description("减法运算")]
        public int plus(int a, int b)
        {
            return a - b;
        }
        [CustomAttribute.Name("乘法")]//调用的是构造函数
        [CustomAttribute.Description("乘法运算")]
        public int Multiply(int a, int b)
        {
            return a * b;
        }
        [CustomAttribute.Name("除法")]
        [CustomAttribute.Description("除法运算")]
        public int division(int a, int b)
        {
            return a / b;
        }
        int aa;
        [CustomAttribute.Name("字段A")]
        [CustomAttribute.Description("(*^__^*) 嘻嘻……A")]
        public int Aa
        {
            get { return aa; }
            set { aa = value; }
        }
        int bb;
        [CustomAttribute.Name("字段B")]
        [CustomAttribute.Description("(*^__^*) 嘻嘻……B")]
        public int Bb
        {
            get { return bb; }
            set { bb = value; }
        }
    }
}

但是还是没有出现那个效果啊,不要急,下部就会出现:

创建一个应用程序(此处要把自定义的Dll加进去,同时还用到了反射的知识):

界面如下:

.net的反射与属性_第3张图片

主要看详细信息这一块:名称。。。功能描述。。。。再看看上面应用的属性的DLL是不是这一块内容!

实现代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Reflection;

namespace Reflect
{
    public partial class FrmMain : Form
    {
        public FrmMain()
        {
            InitializeComponent();
        }
        OpenFileDialog OFD = new OpenFileDialog();
        string[] dllFiles;
        Assembly ass;
        MethodInfo[] Methods;
        PropertyInfo[] Propertis;
        EventInfo[] Events;
        MethodInfo E_Methods;
        ParameterInfo[] Params;

        private void btnBrowse_Click(object sender, EventArgs e)
        {
            OFD.Multiselect = true;
            if (OFD.ShowDialog() == DialogResult.OK)
            {
                dllFiles = OFD.FileNames;
            }
            textBox1.Text = dllFiles[0].Substring(0, dllFiles[0].LastIndexOf("\\"));
            foreach (string FileDll in dllFiles)
            {
                this.lbxDLL.Items.Add(FileDll.Substring(FileDll.LastIndexOf("\\") + 1));
            }
        }

        private void lbxP_SelectedIndexChanged(object sender, EventArgs e)
        {
            richTextBox1.Text = "属性类型:\n";
            richTextBox1.AppendText(Propertis[lbxP.SelectedIndex].Name + " " + Propertis[lbxP.SelectedIndex].PropertyType.ToString());
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            if (lbxDLL.SelectedItem == null)
            {
                MessageBox.Show("请您选择一个数据集!");
                return;
            }
            ass = Assembly.LoadFile(dllFiles[lbxDLL.SelectedIndex]);
            Type type = ass.GetType(txtNamespace.Text+"."+txtClassName.Text);

            Methods = type.GetMethods();
            Propertis = type.GetProperties();
            Events = type.GetEvents();
            lbxM.Items.Clear();
            foreach (MethodInfo TempMethod in Methods)
            {
                if (TempMethod.IsPublic)
                {
                    lbxM.Items.Add(TempMethod.Name);
                }
            }
            lbxP.Items.Clear();
            foreach (PropertyInfo TempProperty in Propertis)
            {
                lbxP.Items.Add(TempProperty.Name);
            }
            lbxE.Items.Clear();
            foreach (EventInfo TempEvent in Events)
            {
                lbxE.Items.Add(TempEvent.Name);
            }
        }

        private void lbxM_SelectedIndexChanged(object sender, EventArgs e)
        {
            Params = Methods[lbxM.SelectedIndex].GetParameters();
            richTextBox1.Text = "参数:\n";
            lbxMP.Items.Clear();
            foreach (ParameterInfo tempParam in Params)
            {
                richTextBox1.AppendText(tempParam.ParameterType.ToString() + " " + tempParam.Name + "\n");
                lbxMP.Items.Add(tempParam.ToString());
            }  
            Type type=typeof(CustomAttribute.Name);
           
            object[] objs = Methods[lbxM.SelectedIndex].GetCustomAttributes(type, true);
            if (objs.Length == 1)
            {
                CustomAttribute.Name name = (CustomAttribute.Name)objs[0];
                richTextBox1.AppendText("\n名称:" + name.Name1);
            }

            Type typeD = typeof(CustomAttribute.Description);
            object[] objsD = Methods[lbxM.SelectedIndex].GetCustomAttributes(typeD, true);
            if (objsD.Length == 1)
            {
                CustomAttribute.Description Des = (CustomAttribute.Description)objsD[0];
                richTextBox1.AppendText("\n" + "功能描述:" + Des.Desc1);
            }        

            txtParam.Text = "";
            lbxMPValue.Items.Clear();
            richTextBox2.Text = "";
        }

        private void lbxE_SelectedIndexChanged(object sender, EventArgs e)
        {
            E_Methods = Events[lbxE.SelectedIndex].GetRaiseMethod();
            richTextBox1.Text = "消息处理函数\n";
            richTextBox1.AppendText(E_Methods.Name);
            richTextBox1.AppendText("函数参数\n");
            foreach (ParameterInfo TempParam in E_Methods.GetParameters())
            {
                richTextBox1.AppendText(TempParam.ParameterType.ToString() + "  " + TempParam.Name + "\n");
            }
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            if (txtParam.Text.Trim() == "" || lbxMP.SelectedItem == null)
            {
                MessageBox.Show("确定参数选中或是参数已赋值!");
                return;
            }

            lbxMPValue.Items.Add(lbxMP.SelectedItem.ToString() + ":   " + txtParam.Text);
            txtParam.Text = "";
        }

        private void btnDel_Click(object sender, EventArgs e)
        {
            if (lbxMPValue.SelectedItem == null)
            {
                MessageBox.Show("确定选中删除参数!");
                return;
            }
            lbxMPValue.Items.Remove(lbxMPValue.Items[lbxMPValue.SelectedIndex]);
        }
        object[] Param_Ms;
        private void btnRun_Click(object sender, EventArgs e)
        {
            object obj = ass.CreateInstance(txtNamespace.Text + "." + txtClassName.Text);
            Param_Ms = new object[lbxMPValue.Items.Count];
            for (int i = 0; i < lbxMPValue.Items.Count; i++)
            {
                Param_Ms[i]=Int32.Parse(lbxMPValue.Items[i].ToString().Split(':')[1].Trim());
            }
            richTextBox2.Text = "运行结果:\n";
            richTextBox2.AppendText(Methods[lbxM.SelectedIndex].Invoke(obj, Param_Ms).ToString());
        }

        private void FrmMain_Load(object sender, EventArgs e)
        {
            txtNamespace.Text = "ClassLibrary1";
            txtClassName.Text = "Class1";
        }
    }
}

这部分代码是反射和属性的结合,其中看这部分:

.net的反射与属性_第4张图片

欢迎大家留言!

你可能感兴趣的:(.net的反射与属性)