Skip to content

Instantly share code, notes, and snippets.

@wilson0x4d
Created May 30, 2015 01:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wilson0x4d/a053c0fd57892d357b2c to your computer and use it in GitHub Desktop.
Save wilson0x4d/a053c0fd57892d357b2c to your computer and use it in GitHub Desktop.
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