以下為本次實踐代碼:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleTest
{
class Program
{
static void Main(string[] args)
{
//反射讀取類私有屬性
Person per = new Person("ismallboy", "20102100104");
Type t = per.GetType();
//獲取私有方法
MethodInfo method = t.GetMethod("GetStuInfo", BindingFlags.NonPublic | BindingFlags.Instance);
//訪問無參數私有方法
string strTest = method.Invoke(per, null).ToString();
//訪問有參數私有方法
MethodInfo method2 = t.GetMethod("GetValue", BindingFlags.NonPublic | BindingFlags.Instance);
object[] par = new object[2];
par[0] = "ismallboy";
par[1] = 2;
string strTest2 = method2.Invoke(per, par).ToString();
//獲取私有字段
PropertyInfo field = t.GetProperty("Name", BindingFlags.NonPublic | BindingFlags.Instance);
//訪問私有字段值
string value = field.GetValue(per).ToString();
//設置私有字段值
field.SetValue(per, "new Name");
value = field.GetValue(per).ToString();
}
}
/// <summary>
/// 個人信息
/// </summary>
class Person
{
private string Name { get; set; }
private string StuNo { get; set; }
public Person(string name, string stuNo)
{
this.Name = name;
this.StuNo = stuNo;
}
private string GetStuInfo()
{
return this.Name;
}
private string GetValue(string str, int n)
{
return str + n.ToString();
}
}
}
如果使用dynamic的話,也可以如下:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleTest
{
class Program
{
static void Main(string[] args)
{
//反射讀取類私有屬性
dynamic per = new Person("ismallboy", "20102100104");
Type t = per.GetType();
//獲取私有方法
MethodInfo method = t.GetMethod("GetStuInfo", BindingFlags.NonPublic | BindingFlags.Instance);
//訪問無參數私有方法
string strTest = method.Invoke(per, null);
//訪問有參數私有方法
MethodInfo method2 = t.GetMethod("GetValue", BindingFlags.NonPublic | BindingFlags.Instance);
object[] par = new object[2];
par[0] = "ismallboy";
par[1] = 2;
string strTest2 = method2.Invoke(per, par);
//獲取私有字段
PropertyInfo field = t.GetProperty("Name", BindingFlags.NonPublic | BindingFlags.Instance);
//訪問私有字段值
string value = field.GetValue(per);
//設置私有字段值
field.SetValue(per, "new Name");
value = field.GetValue(per);
}
}
/// <summary>
/// 個人信息
/// </summary>
class Person
{
private string Name { get; set; }
private string StuNo { get; set; }
public Person(string name, string stuNo)
{
this.Name = name;
this.StuNo = stuNo;
}
private string GetStuInfo()
{
return this.Name;
}
private string GetValue(string str, int n)
{
return str + n.ToString();
}
}
}