Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Actually, I can't get it to <em>fail</em> - at least, when generating in memory.</p> <p>Let's start simply, with a <code>public readonly</code> field (so we aren't breaking any accessebility rules); my first attempt is as below, and it works fine:</p> <pre><code>using System; using System.Reflection; using System.Reflection.Emit; class Foo { public readonly int i; public int I { get { return i; } } public Foo(int i) { this.i = i; } } static class Program { static void Main() { var setter = CreateWriteAnyInt32Field(typeof(Foo), "i"); var foo = new Foo(123); setter(foo, 42); Console.WriteLine(foo.I); // 42; } static Action&lt;object, int&gt; CreateWriteAnyInt32Field(Type type, string fieldName) { var field = type.GetField(fieldName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); var method = new DynamicMethod("evil", null, new[] { typeof(object), typeof(int) }); var il = method.GetILGenerator(); il.Emit(OpCodes.Ldarg_0); il.Emit(OpCodes.Castclass, type); il.Emit(OpCodes.Ldarg_1); il.Emit(OpCodes.Stfld, field); il.Emit(OpCodes.Ret); return (Action&lt;object, int&gt;)method.CreateDelegate(typeof(Action&lt;object, int&gt;)); } } </code></pre> <p>The only time it gets interesting is if the field is <code>private</code>:</p> <pre><code>private readonly int i; </code></pre> <p>The code above then gives the oh-so-vague:</p> <blockquote> <p>Operation could destabilize the runtime.</p> </blockquote> <p>But we get around that by pretending that the method is inside the field's declaring type:</p> <pre><code>var method = new DynamicMethod("evil", null, new[] { typeof(object), typeof(int) }, field.DeclaringType); </code></pre> <p>Some other internal checks can be done by enabling <code>skipVisibility</code>:</p> <pre><code>var method = new DynamicMethod("evil", null, new[] { typeof(object), typeof(int) }, field.DeclaringType, true); </code></pre> <p>However, note that not all of this is possible if generating standalone assemblies. You are held to much higher standards when creating actual dlls. For this reason, the <code>precompiler</code> tool (to pre-generate assemblies) cannot handle quite the same range of scenarios that the in-memory meta-programming code can.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload