1. 程式人生 > >C#中使用typeof關鍵字和GetType()獲取類的內部結構(反射機制)

C#中使用typeof關鍵字和GetType()獲取類的內部結構(反射機制)

一、問題描述

java有反射機制,C#也有反射機制,在C#中typeof關鍵字用於獲取型別的System.Type物件,該物件的GetMethods()方法可以得到型別中定義的方法物件的計集合,呼叫方法集合中每個方法物件的GetParameters()可以得到每個方法的引數集合,但是需要引用Reflection名稱空間。

        獲取System.Type物件有兩種方法:第一種是用typeof關鍵字,第二種是用物件引用呼叫GetType()方法

1、System.Type type =  typeof(System.Int32);   //引數是一種系統型別

2、 string str= “test”;     

              System.Type type = str.GetType();    //用物件引用呼叫GetType()方法

二、解決步驟

1、在程式碼中引用Reflection名稱空間

using System.Reflection;

2、可以用typeof關鍵字,也可以用GetType()方法獲取類的內部結構

三、程式碼演示

1、獲取String類的的所有方法和引數並顯示。

程式碼:

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 test1
{
    public partial class Form7 : Form
    {
        public Form7()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //Type type = typeof(System.String);
            String str = "test";
            Type type = str.GetType();
            foreach (MethodInfo method in type.GetMethods())
            {
                out_rtb.AppendText("方法名稱:"+method.Name+Environment.NewLine);
                foreach (ParameterInfo param in method.GetParameters())
                {
                    out_rtb.AppendText("\t引數:" + param.Name + Environment.NewLine);
                }
            }
        }
    }
}

2、提示錯誤資訊後,將所有CheckBox控制元件內容清空


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 test1
{
    public partial class Form6 : Form
    {
        public Form6()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            byte input1,input2;
            if (byte.TryParse(input1_tbx.Text, out input1) && byte.TryParse(input2_tbx.Text, out input2))
            {
                try
                {
                    checked
                    {
                        input1 += input2;
                    }
                    result_tbx.Text = input1.ToString();
                }
                catch (OverflowException ex)
                {
                    MessageBox.Show(ex.Message, "錯誤資訊");
                }
            }
            else
            {
                MessageBox.Show("請輸入小於255的數字!", "提示資訊");               
            }

            //清空輸入資訊
            foreach (Control c in Controls)
            {
                if (c.GetType() == typeof(TextBox))
                {
                    ((TextBox)c).Clear();
                }
            }
        }

    }
}