0
Я пишу код с помощью DynamicMethod. Внутри моего DynamicMethod я хочу вызвать свойства Nullable.HasValue (а также Nullable.Value). Я написал некоторый код, чтобы сделать некоторые, но я продолжаю получать Operation could destabilize the runtime error
.Как вызвать Nullable.HasValue в DynamicMethod?
Вот мой код:
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Reflection.Emit;
namespace Test
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(testHasValue()(true));
}
delegate bool HasValueDelegate(bool? a);
static HasValueDelegate testHasValue()
{
MethodInfo GetNullableHasValue = typeof(bool?).GetProperty("HasValue").GetGetMethod();
DynamicMethod method = new DynamicMethod("Wow", typeof(bool), new Type[] { typeof(bool?) });
ILGenerator generator = method.GetILGenerator();
MethodInfo GetNullableValue = typeof(bool?).GetProperty("Value").GetGetMethod();
generator.Emit(OpCodes.Ldarg_0);
// Callvirt results in the same error.
generator.Emit(OpCodes.Call, GetNullableHasValue);
generator.Emit(OpCodes.Ret);
return ((HasValueDelegate)(method.CreateDelegate(typeof(HasValueDelegate)))).Invoke;
}
}
}
Я хотел бы добавить, что в соответствии с Telerik JustDecompile, С # код, чтобы вернуть собственность HasValue выливается IL имеет следующие:
static bool hasValue(bool? a)
{
return a.HasValue;
}
.method private hidebysig static bool hasValue (
valuetype [mscorlib]System.Nullable`1<bool> a
) cil managed
{
IL_0000: ldarga.s a
IL_0002: call instance bool valuetype [mscorlib]System.Nullable`1<bool>::get_HasValue()
IL_0007: ret
}
Я хотел бы добавить, что с помощью отражения для вызова 'GetNullableValue' работает отлично. –