Assign fields to record type - CSharp System.Reflection

CSharp examples for System.Reflection:FieldInfo

Description

Assign fields to record type

Demo Code


using System.Reflection.Emit;
using System.Reflection;
using System.Collections.Generic;
using System;//from   ww  w .j av a 2s.  c  o  m

public class Main{
        /// <summary>
        /// Assign fields to record type
        /// </summary>
        /// <param name="recordType">Class to base function on</param>
        /// <param name="fields">List of fields to assign</param>
        /// <returns>function that assigns only</returns>
        public static AssignDelegate AssignValuesMethod(Type recordType, FieldInfo[] fields)
        {
            var dm = new DynamicMethod("FileHelpersDynamic_Assign",
                                       MethodAttributes.Static | MethodAttributes.Public,
                                       CallingConventions.Standard,
                                       null,
                                       new[] {typeof(object), typeof(object[]) },
                                       recordType,
                                       true);

            var generator = dm.GetILGenerator();

            generator.DeclareLocal(recordType);
            generator.Emit(OpCodes.Ldarg_0);
            generator.Emit(OpCodes.Castclass, recordType);
            generator.Emit(OpCodes.Stloc_0);

            for (int i = 0; i < fields.Length; i++)
            {
                var field = fields[i];

                generator.Emit(OpCodes.Ldloc_0);
                generator.Emit(OpCodes.Ldarg_1);
                generator.Emit(OpCodes.Ldc_I4, i);
                generator.Emit(OpCodes.Ldelem_Ref);

                if (field.FieldType.IsValueType)
                {
                    generator.Emit(OpCodes.Unbox_Any, field.FieldType);
                }
                else
                {
                    generator.Emit(OpCodes.Castclass, field.FieldType);
                }

                generator.Emit(OpCodes.Stfld, field);
            }

            generator.Emit(OpCodes.Ret);

            return (AssignDelegate)dm.CreateDelegate(typeof(AssignDelegate));
        }
}

Related Tutorials