csharp/1996v/Bssom.Net/Bssom.Serializer/Internal/EmitHelper.cs

EmitHelper.cs
//using System.Runtime.CompilerServices;
using System;
using System.Reflection;
using System.Reflection.Emit;

namespace Bssom.Serializer.Internal
{
    internal static clast EmitHelper
    {
        public static void EmitDefault(this ILGenerator il, Type type)
        {
            switch (Type.GetTypeCode(type))
            {
                case TypeCode.DateTime:
                    il.Emit(OpCodes.Ldsfld, typeof(DateTime).GetField(nameof(DateTime.MinValue)));
                    return;
                case TypeCode.Decimal:
                    il.Emit(OpCodes.Ldsfld, typeof(decimal).GetField(nameof(decimal.Zero)));
                    return;
                case TypeCode.Boolean:
                case TypeCode.Char:
                case TypeCode.SByte:
                case TypeCode.Byte:
                case TypeCode.Int16:
                case TypeCode.UInt16:
                case TypeCode.Int32:
                case TypeCode.UInt32:
                    il.Emit(OpCodes.Ldc_I4_0);
                    return;

                case TypeCode.Int64:
                case TypeCode.UInt64:
                    il.Emit(OpCodes.Ldc_I4_0);
                    il.Emit(OpCodes.Conv_I8);
                    return;

                case TypeCode.Single:
                    il.Emit(OpCodes.Ldc_R4, default(float));
                    return;

                case TypeCode.Double:
                    il.Emit(OpCodes.Ldc_R8, default(double));
                    return;
            }

            if (type.IsValueType)
            {
                LocalBuilder lb = il.DeclareLocal(type);
                il.Emit(OpCodes.Ldloca, lb);
                il.Emit(OpCodes.Initobj, type);
                il.Emit(OpCodes.Ldloc, lb);
            }
            else
            {
                il.Emit(OpCodes.Ldnull);
            }
        }

        public static void EmitStloc(this ILGenerator il, int index)
        {
            switch (index)
            {
                case 0:
                    il.Emit(OpCodes.Stloc_0);
                    break;
                case 1:
                    il.Emit(OpCodes.Stloc_1);
                    break;
                case 2:
                    il.Emit(OpCodes.Stloc_2);
                    break;
                case 3:
                    il.Emit(OpCodes.Stloc_3);
                    break;
                default:
                    if (index