1.首先建立一个类
class PropertyClass
{
public PropertyClass()
{
}
public PropertyClass(ref Int32 x)
{
x *= 5;
}
public int fieldValue = 0;
private string name;
public string Name
{
get { return name; }
set { name = value; }
}
public int GetInt(int value)
{
return value;
}
public void Display(string str)
{
Console.WriteLine(str);
}
public override String ToString()
{
return fieldValue.ToString();
}
}
2.用反射的方式调用这个PropertyClass类中的方法
public static void instanceLove()
{
PropertyClass propertyClass = new PropertyClass();
Type type = propertyClass.GetType();
//Type type = typeof(propertyClass);效果和上面语句一样,只是写法不同。
object obj = type.InvokeMember(null, BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.CreateInstance, null, null, new object[] { });
//调用没有返回值的方法
//运行之后的结果[Hello World]
type.InvokeMember("Display", BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Instance, null, obj, new object[] { "Hello World" });
//调用有返回值的方法
//运行之后的结果[1982]
int i = (int)type.InvokeMember("GetInt", BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Instance, null, obj, new object[] { 1982 });
//设置属性值
//此时的Name 's Value为[My Name is Brian Lei]
type.InvokeMember("Name", BindingFlags.SetProperty, null, obj, new object[] { "My Name is Brian Lei" });
//获取属性值
//运行之后的结果[My Name is Brian Lei]
string str = (string)type.InvokeMember("Name", BindingFlags.GetProperty, null, obj, null);
//设置字段值
type.InvokeMember("fieldValue", BindingFlags.SetField, null, obj, new object[] { 813 });
//获取字段值
//运行之后的结果[813]
int f = (int)type.InvokeMember("fieldValue", BindingFlags.GetField, null, obj, null);
//调用override方法
//运行之后的结果[813]
String s = (String)type.InvokeMember("ToString", BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.InvokeMethod, null, obj, null);
//调用构造方法
//运行之后的结果[8*5=40]
Object objs = type.InvokeMember(null,BindingFlags.DeclaredOnly |BindingFlags.Public | BindingFlags.NonPublic |BindingFlags.Instance | BindingFlags.CreateInstance, null, null, new Object[] { 8 });
}
3.写个Main函数测试一下
class EntryPoint
{
static void Main()
{
Test.instanceLove();
}
}