Created
May 30, 2015 01:40
-
-
Save wilson0x4d/a053c0fd57892d357b2c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using Microsoft.VisualStudio.TestTools.UnitTesting; | |
namespace CanwriteReadOnlyReflection | |
{ | |
[TestClass] | |
public class UnitTest1 | |
{ | |
public class TargetType | |
{ | |
private readonly object _foo; | |
public object Foo { get { return _foo; } } | |
} | |
[TestMethod] | |
public void TestMethod1() | |
{ | |
// instance | |
var target = new TargetType(); | |
// reflected type, can be obtained through several other means | |
var reflection = target.GetType(); | |
// reflected field | |
var field = reflection.GetField("_foo", System.Reflection.BindingFlags.GetField | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic); | |
field.SetValue(target, "bar"); | |
// assert that private readonly instance member has been modified by fetched it via read-only public property | |
Assert.AreEqual("bar", target.Foo); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment