Note that there are some explanatory texts on larger screens.

plurals
  1. POUsing expression trees to construct an object with unknown members
    primarykey
    data
    text
    <p>I'm trying to create a generic function that will take 2 instances of a struct and create a new instance using the values of the passed-in instances. I'm mostly there but I'm having trouble figuring out how to build the expression tree to take the new values as parameters in the MemberInit (first time using expression trees).</p> <p>I'm trying to avoid creating garbage (so no boxing) as much as possible.</p> <p>Here's what I have so far:</p> <pre><code>private static readonly Dictionary&lt;Type, FieldInfo[]&gt; fieldInfoCache = new Dictionary&lt;Type, FieldInfo[]&gt;(); private static readonly Dictionary&lt;FieldInfo, dynamic&gt; compiledDelegates = new Dictionary&lt;FieldInfo, dynamic&gt;(); private static T Lerp&lt;T&gt;(T start, T end, float amount) where T : new() { FieldInfo[] fields; var type = typeof(T); if(!fieldInfoCache.TryGetValue(type, out fields)) { fields = typeof(T).GetFields(BindingFlags.Public | BindingFlags.Instance); fieldInfoCache.Add(type, fields); } var binds = new List&lt;MemberBinding&gt;(); foreach(var fieldInfo in fields) { dynamic getter; if(!compiledDelegates.TryGetValue(fieldInfo, out getter)) { var targetExp = Expression.Parameter(type, type.Name); var fieldExp = Expression.Field(targetExp, fieldInfo); getter = Expression.Lambda(typeof(Func&lt;,&gt;).MakeGenericType(type, fieldInfo.FieldType), fieldExp, targetExp).Compile(); compiledDelegates.Add(fieldInfo, getter); } var startVal = getter.Invoke(start); var endVal = getter.Invoke(end); //This needs to be assigned to something var newVal = fieldInfo.FieldType.IsAssignableFrom(typeof(float)) ? LerpF(startVal, endVal, amount) : Lerp(startVal, endVal, amount); var fieldParamExp = Expression.Parameter(fieldInfo.FieldType, "newVal"); var bind = Expression.Bind(fieldInfo, fieldParamExp); binds.Add(bind); } //How do I fix these two lines? var memberInit = Expression.MemberInit(Expression.New(type), binds); var result = Expression.Lambda&lt;Func&lt;T&gt;&gt;(memberInit).Compile().Invoke(); return result; } </code></pre> <p>The part that I'm stumped on is how to feed the values into those last 2 lines without causing boxing</p>
    singulars
    1. This table or related slice is empty.
    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.
 

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