我有这样的代码来发出加载整数或字符串值的 IL 代码。但我不知道如何向其添加 decimal
类型。 Emit
方法不支持它。有什么解决办法吗?
ILGenerator ilGen = methodBuilder.GetILGenerator();
if (type == typeof(int))
{
ilGen.Emit(OpCodes.Ldc_I4, Convert.ToInt32(value, CultureInfo.InvariantCulture));
}
else if (type == typeof(double))
{
ilGen.Emit(OpCodes.Ldc_R8, Convert.ToDouble(value, CultureInfo.InvariantCulture));
}
else if (type == typeof(string))
{
ilGen.Emit(OpCodes.Ldstr, Convert.ToString(value, CultureInfo.InvariantCulture));
}
不工作:
else if (type == typeof(decimal))
{
ilGen.Emit(OpCodes.Ld_???, Convert.ToDecimal(value, CultureInfo.InvariantCulture));
}
编辑: 好吧,这就是我所做的:
else if (type == typeof(decimal))
{
decimal d = Convert.ToDecimal(value, CultureInfo.InvariantCulture);
// Source: https://msdn.microsoft.com/en-us/library/bb1c1a6x.aspx
var bits = decimal.GetBits(d);
bool sign = (bits[3] & 0x80000000) != 0;
byte scale = (byte)((bits[3] >> 16) & 0x7f);
ilGen.Emit(OpCodes.Ldc_I4, bits[0]);
ilGen.Emit(OpCodes.Ldc_I4, bits[1]);
ilGen.Emit(OpCodes.Ldc_I4, bits[2]);
ilGen.Emit(sign ? OpCodes.Ldc_I4_1 : OpCodes.Ldc_I4_0);
ilGen.Emit(OpCodes.Ldc_I4, scale);
var ctor = typeof(decimal).GetConstructor(new[] { typeof(int), typeof(int), typeof(int), typeof(bool), typeof(byte) });
ilGen.Emit(OpCodes.Newobj, ctor);
}
但它不会生成newobj
操作码,而是生成nop
和STLoc.0
。找到构造函数并将其传递给 Emit
调用。这里出了什么问题?显然,在尝试执行生成的代码时会抛出 InvalidProgramException
,因为堆栈完全困惑了。
最佳答案
来吧,只需反编译一些执行相同操作的 C# 代码 - 您会看到没有十进制原语。
42M
编译为
ldc.i4.s 2A
newobj System.Decimal..ctor
对于十进制数,这要复杂得多:
42.3M
给予
ldc.i4 A7 01 00 00
ldc.i4.0
ldc.i4.0
ldc.i4.0
ldc.i4.1
newobj System.Decimal..ctor
获取任意小数的最简单方法是使用构造函数的 int[]
重载和 GetBits
静态方法。您还可以对 SetBits
方法进行逆向工程,以允许您使用适当的值调用更简单的构造函数,或使用反射来读取内部状态 - 有很多选择。
编辑:
你很接近,但你破坏了 ILGen - 虽然构造函数的最后一个参数是 byte
,但你正在加载的常量必须是 整数
。以下按预期工作:
var bits = decimal.GetBits(d);
bool sign = (bits[3] & 0x80000000) != 0;
int scale = (byte)((bits[3] >> 16) & 0x7f);
gen.Emit(OpCodes.Ldc_I4, bits[0]);
gen.Emit(OpCodes.Ldc_I4, bits[1]);
gen.Emit(OpCodes.Ldc_I4, bits[2]);
gen.Emit(sign ? OpCodes.Ldc_I4_1 : OpCodes.Ldc_I4_0);
gen.Emit(OpCodes.Ldc_I4, scale);
var ctor = typeof(decimal).GetConstructor(new[] { typeof(int), typeof(int),
typeof(int), typeof(bool), typeof(byte) });
gen.Emit(OpCodes.Newobj, ctor);
gen.Emit(OpCodes.Ret);
编辑 2:
一个简单的示例,说明如何使用表达式树(在本例中树是由 C# 编译器构建的,但这取决于您)定义动态方法体:
var assembly = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName("Test"),
AssemblyBuilderAccess.Run);
var module = assembly.DefineDynamicModule("Test");
var type = module.DefineType("TestType");
var methodBuilder = type.DefineMethod("MyMethod", MethodAttributes.Public
| MethodAttributes.Static);
methodBuilder.SetReturnType(typeof(decimal));
Expression<Func<decimal>> decimalExpression = () => 42M;
decimalExpression.CompileToMethod(methodBuilder);
var t = type.CreateType();
var result = (decimal)t.GetMethod("MyMethod").Invoke(null, new object[] {});
result.Dump(); // 42 :)
关于c# - 发出 IL 代码以加载十进制值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33570554/