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;
using Models;
namespace test
{
public partial class Form3 : Form
{
public Form3()
{
InitializeComponent();
}
//从程序集中获取指定对象类型;
Type type = assembly2.GetType("Models.User");
//使用Activator创建一个实例使用Activator创建一个实例
User user2 = Activator.CreateInstance(type) as User;
//通过对象类型创建对象实例
User user = assembly.CreateInstance("Models.User") as User;
// 调用无参构造
ConstructorInfo studentConstructor = type.GetConstructor(new Type[] { });
User user3 = studentConstructor.Invoke(new object[] { }) as User;
//调用有参构造
ConstructorInfo studentConstructor2 = type.GetConstructor(new Type[] { typeof(string) });
User user4 = studentConstructor.Invoke(new object[] { "您调用了有参构造创建了一个类实例。"}) as User;
//调用非静态方法
string returnValue = type.InvokeMember("PublicClassMethod", BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Instance, null, user, new object[] { }) as string;
// 调用静态方法 .
string returnValue2 = type.InvokeMember("StaticMethod", BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Static, null, user, new object[] { }) as string;
// 调用私有方法 .
string returnValue3 = type.InvokeMember("PrivateClassMethod", BindingFlags.InvokeMethod | BindingFlags.NonPublic | BindingFlags.Instance, null, user, new object[] { }) as string;
ParameterInfo[] paras = parameterMethod.GetParameters();
for (int i = 0; i < paras.Length; i++)
{
MessageBox.Show(string.Format("参数名称:{0},参数类型:{1},是否可选:{2},位置:{3},默认值:{4}", paras[i].Name, paras[i].ParameterType.ToString(), paras[i].IsOptional.ToString(), paras[i].Position.ToString(), paras[i].DefaultValue.ToString()));