Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Any properties that are value-types (<code>int</code> etc) will need boxing; or you will need to use a different <code>Append</code> overload.</p> <p>Also:</p> <ul> <li>you need to load the object each time (arg0)</li> <li><code>StringBuilder.Append</code> is a fluent API; you either need to pop the value, or re-use it:</li> <li>as a consequence, you don't need the field</li> </ul> <p>(personally, though, I'd return a <code>string</code>, but "meh")</p> <p>Like so:</p> <pre><code> DynamicAccessor&lt;T&gt; dynAccessor = new DynamicAccessor&lt;T&gt;(); MethodInfo AppendMethod = typeof(StringBuilder).GetMethod("Append", new[] { typeof(Object) }); //Append method of Stringbuilder var method = new DynamicMethod("ClassWriter", typeof(StringBuilder), new[] { typeof(T) }, typeof(T), true); var generator = method.GetILGenerator(); generator.Emit(OpCodes.Newobj, typeof(StringBuilder).GetConstructor(Type.EmptyTypes)); //make our string builder //iterate through all the instance of T's props and sb.Append their values. PropertyInfo[] props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (var info in props) { generator.Emit(OpCodes.Ldarg_0); generator.Emit(OpCodes.Callvirt, info.GetGetMethod()); //call the Getter if (info.PropertyType.IsValueType) { generator.Emit(OpCodes.Box, info.PropertyType); } generator.Emit(OpCodes.Callvirt, AppendMethod); //Call Append } generator.Emit(OpCodes.Ret); //return pointer to sb </code></pre> <p>This generates the equivalent to:</p> <pre><code>StringBuilder ClassWriter(T obj) { return new StringBuilder.Append((object)obj.Foo).Append((object)obj.Bar) .Append((object)obj.Blip).Append((object)obj.Blap); } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

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