反射

一、方法带参数
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Linq.Dynamic;
using System.Reflection;
using System.Text.RegularExpressions;

 

namespace Demo
{
public partial class Form6 : Form
{
public Form6()
{
InitializeComponent();
}

private void Form6_Load(object sender, EventArgs e)
{

//Assembly assembly = Assembly.Load("Demo");

Assembly assembly = Assembly.Load(Assembly.GetExecutingAssembly().ToString());

Type type = assembly.GetType("Demo.Form6");


MethodInfo met = type.GetMethod("Add");
object obj = Activator.CreateInstance(type, null);
Object[] num = { 10, 11 };
MessageBox.Show(met.Invoke(obj, num).ToString());

}

public int Add(int p1, int p2)
{
return p1 + p2;
}

 

}

}
View Code
二、方法属性赋值
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Linq.Dynamic;
using System.Reflection;
using System.Text.RegularExpressions;

namespace Demo
{
public partial class Form6 : Form
{
public Form6()
{
InitializeComponent();
}

private void Form6_Load(object sender, EventArgs e)
{
//Assembly asm = Assembly.Load("Demo");

Assembly assembly = Assembly.Load(Assembly.GetExecutingAssembly().ToString());
var type = asm.GetType("Demo.Test");

var instance = asm.CreateInstance("Demo.Test");

type.GetProperty("Name").SetValue(instance, "http://greenerycn.cnblogs.com", null);
type.GetProperty("Id").SetValue(instance, 1, null);

var method = type.GetMethod("Hello");
method.Invoke(instance, null);

}
}

public class Test
{
private int id;
private string name;

public int Id
{
get { return this.id; }
set { this.id = value; }
}

public string Name
{
get { return this.name; }
set { this.name = value; }
}

public void Hello()
{
MessageBox.Show(Name);
}
}

}
View Code
原文地址:https://www.cnblogs.com/hanmian4511/p/5473016.html