-
Notifications
You must be signed in to change notification settings - Fork 0
/
Program.cs
42 lines (36 loc) · 1.12 KB
/
Program.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
namespace SettingPrivateField
{
using System;
using System.Reflection;
class Program
{
public class Person
{
private string name;
public string Name
{
get { return name; }
private set { name = value; }
}
public Person(string name)
{
this.name = name;
}
}
public static void SetField<T>(T instance, string fieldName, object obj)
{
var f = typeof(T).GetField(fieldName, BindingFlags.Instance | BindingFlags.NonPublic);
if (obj.GetType() != f.FieldType)
throw new InvalidOperationException("Types do not match!");
f.SetValue(instance, obj);
}
static void Main(string[] args)
{
var person = new Person("John");
Console.WriteLine(string.Format("My name is {0}!", person.Name));
SetField(person, "name", "Jason");
Console.WriteLine(string.Format("My name is {0}!", person.Name));
Console.ReadKey();
}
}
}