DynamicMethod を使用してコードを書いています。DynamicMethod 内で、Nullable.HasValue (および Nullable.Value) プロパティを呼び出したいと考えています。私はいくつかのコードを書きましたが、Operation could destabilize the runtime error
.
これが私のコードです:
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 プロパティを返す C# コードが 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
}