using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
MyClass myclass = new MyClass();
FieldInfo fieldInfo_name = typeof(MyClass).GetField("name", BindingFlags.NonPublic | BindingFlags.Instance);
FieldInfo fieldInfo_age= typeof(MyClass).GetField("age",BindingFlags.NonPublic|BindingFlags.Instance);
fieldInfo_name.SetValue(myclass, "Du_zhiyong");
fieldInfo_age.SetValue(myclass, "24岁");
Console.BackgroundColor = ConsoleColor.Green;
Console.WriteLine(myclass.ToString());
Console.Read();
}
}
class MyClass
{
//私有字段
private string name;
//私有字段
private string age;
public override string ToString()
{
return string.Format("Name:{0},Age:{1}", name, age);
}
}
}
结果: Name:Du_zhiyong,Age:24岁