public class Love
{
public int field1;
private string _name;
public Love()
{
}
public string Name
{
get
{
return _name;
}
set
{
_name = value;
}
}
public int GetInt(int a)
{
return a;
}
public void Display(string str)
{
System.Windows.Forms.MessageBox.Show(str);
}
}
{
public int field1;
private string _name;
public Love()
{
}
public string Name
{
get
{
return _name;
}
set
{
_name = value;
}
}
public int GetInt(int a)
{
return a;
}
public void Display(string str)
{
System.Windows.Forms.MessageBox.Show(str);
}
}
测试代码:
private void test()
{
Love love = new Love();
Type type = love.GetType();
type.InvokeMember("Display", BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Instance, null, love, new object[] { "aldfjdlf" });
//调用有返回值的方法
int i = (int)type.InvokeMember("GetInt", BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Instance, null, love, new object[] { 1 });
MessageBox.Show(i.ToString());
//设置属性值
type.InvokeMember("Name", BindingFlags.SetProperty, null, love, new string[] { "abc" });
//获取属性值
string str = (string)type.InvokeMember("Name", BindingFlags.GetProperty, null, love, null);
MessageBox.Show(str);
//设置字段值
type.InvokeMember("field1", BindingFlags.SetField, null, love, new object[] { 444 });
//获取公有字段值
int f = (int)type.InvokeMember("field1", BindingFlags.GetField, null, love, null);
MessageBox.Show(f.ToString());
//获取私有字段值
string name = (string)type.InvokeMember("_name", BindingFlags.GetField | BindingFlags.NonPublic |BindingFlags.Instance, null, love, null);
MessageBox.Show(name);
}
{
Love love = new Love();
Type type = love.GetType();
type.InvokeMember("Display", BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Instance, null, love, new object[] { "aldfjdlf" });
//调用有返回值的方法
int i = (int)type.InvokeMember("GetInt", BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Instance, null, love, new object[] { 1 });
MessageBox.Show(i.ToString());
//设置属性值
type.InvokeMember("Name", BindingFlags.SetProperty, null, love, new string[] { "abc" });
//获取属性值
string str = (string)type.InvokeMember("Name", BindingFlags.GetProperty, null, love, null);
MessageBox.Show(str);
//设置字段值
type.InvokeMember("field1", BindingFlags.SetField, null, love, new object[] { 444 });
//获取公有字段值
int f = (int)type.InvokeMember("field1", BindingFlags.GetField, null, love, null);
MessageBox.Show(f.ToString());
//获取私有字段值
string name = (string)type.InvokeMember("_name", BindingFlags.GetField | BindingFlags.NonPublic |BindingFlags.Instance, null, love, null);
MessageBox.Show(name);
}