一、问题描述
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();
}
}
}
}
}