using System;
using System.Reflection;
namespace C15_5
{
public class Student
{
public int i_age;
private string s_name;
public Student()
{
}
public string Name
{
get { return s_name; }
set { s_name = value; }
}
public int GetAge(int age)
{
return age;
}
public void Display(string name)
{
Console.WriteLine(name);
}
}
public class Progaram
{
public static void Main(string[] args)
{
Student stu = new Student();
Type type = stu.GetType();
Object obj = type.InvokeMember(null, BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.CreateInstance, null, null, args);
//叫沒有回傳值的Display方法
type.InvokeMember("Display", BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Instance, null, obj, new object[] { "小小王" });
//叫用有回傳值的GetAge方法
int i = (int)type.InvokeMember("GetAge",BindingFlags.InvokeMethod | BindingFlags.Public |BindingFlags.Instance, null,obj,new object[]{25});
Console.WriteLine(i);
//設置Name 屬性
type.InvokeMember("Name",BindingFlags.SetProperty, null,obj,new string[] {"王強"});
//獲取Name 屬性
string str = (string)type.InvokeMember("Name", BindingFlags.GetProperty,null,obj,null);
Console.WriteLine(str);
//設置i_age欄位
type.InvokeMember("i_age",BindingFlags.SetField, null,obj, new object[]{35});
//獲取i_age欄位值
int f = (int)type.InvokeMember("i_age",BindingFlags.GetField,null,obj,null);
Console.WriteLine(f);
}
}
}
沒有留言:
張貼留言