This can be done using reflection.
public class Person
{
private int age;
private string sex;
readonly private static string name;
readonly private string job;
static Person()
{
name = "initial name";
}
public Person()
{
age = 10;
sex = "male";
job = "none";
}
public int Age
{
get
{
return age;
}
}
public string Job
{
get
{
return job;
}
}
public static string Name
{
get
{
return name;
}
}
public string Sex
{
get
{
return sex;
}
}
}
class Program
{
static void Main(string[] args)
{
Person p = new Person();
Console.WriteLine(p.Job);
Console.WriteLine(Person.Name);
Console.WriteLine(p.Age);
Type type = p.GetType();
FieldInfo nameField = type.GetField("name", BindingFlags.NonPublic | BindingFlags.Static);
nameField.SetValue(null, "NewName");
FieldInfo jobField = type.GetField("job", BindingFlags.NonPublic | BindingFlags.Instance);
jobField.SetValue(p, "New Job");
FieldInfo ageField = type.GetField("age", BindingFlags.NonPublic | BindingFlags.Instance);
ageField.SetValue(p, 20);
Console.WriteLine(p.Job);
Console.WriteLine(Person.Name);
Console.WriteLine(p.Age);
Console.ReadLine();
}
}
Note: Don't forgot to use System.Reflection Namespace.
....................
No comments:
Post a Comment