[转]C#反射获取私有字段
(2016-02-29 11:47:16)
-
转自:http://blog.csdn.net/liyifei21/article/details/34838375
-
-
using System;
-
using System.Collections.Generic;
-
using System.Text;
-
using System.Reflection;
-
namespace ReflectionDemo
-
{
-
class Program
-
{
-
static void Main(string[] args)
-
{
-
Type t = typeof(ChangeValue);
-
Type[] types = new Type[0];//为构造函数准备参数类型
-
ConstructorInfo ci = t.GetConstructor(types); //获得构造函数
-
object[] objs = new object[0];//为构造函数准备参数值
-
object obj = ci.Invoke(objs);//调用构造函数创建对象
-
MethodInfo mi = t.GetMethod("WriteLine");//获得公有的writeline方法
-
mi.Invoke(obj, null);
-
FieldInfo fi = t.GetField("myValue", BindingFlags.NonPublic | BindingFlags.Instance);//获得私有字段
-
FieldInfo[] fis=t.GetFields(BindingFlags.NonPublic | BindingFlags.Instance|BindingFlags.Public);
-
Console.WriteLine(fis.Length);
-
foreach (var fieldInfo in fis)
-
{
-
Console.WriteLine(fieldInfo.GetValue(obj));
-
}
-
fi.SetValue(obj, "new Value"); //改写私有字段
-
mi.Invoke(obj, null);
-
MethodInfo mi2 = t.GetMethod("Write", BindingFlags.NonPublic | BindingFlags.Instance);//获得私有的Write方法
-
mi2.Invoke(obj, null);
-
Console.ReadLine();
-
}
-
}
-
public class ChangeValue
-
{
-
private string myValue = "old Value";
-
public string firstValue = "values1";
-
public void WriteLine()
-
{
-
Console.WriteLine("MyValue is: " + myValue);
-
}
-
private void Write()
-
{
-
Console.WriteLine("MyValue is: " + myValue);
-
}
-
}
-
}
喜欢
0
赠金笔
加载中,请稍候......