.net 反射访问私有变量和私有方法

以下为本次实践代码:

 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", "");
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[];
par[] = "ismallboy";
par[] = ;
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", "");
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[];
par[] = "ismallboy";
par[] = ;
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();
}
}
}
上一篇:(转)unity开发相关环境(vs、MonoDevelop)windows平台编码问题


下一篇:第四届 CCCC 团体程序设计天梯赛 游记