Delegate.CreateDelegate 从 MethodInfo 获取 Func<> 对 double 类型不起作用?
Delegate.CreateDelegate to get Func<> from MethodInfo does not work for double type?
我正在尝试为 double.CompareTo 创建一个函数。
我是这样创建的:
var method = typeof(double).GetMethod("CompareTo", new Type[] { typeof(double) });
var func = (Func<double, double, int>)Delegate.CreateDelegate(typeof(Func<double, double, int>), method);
它适用于 string.CompareTo 像这样:
var method = typeof(string).GetMethod("CompareTo", new Type[] { typeof(string) });
var func = (Func<string, string, int>)Delegate.CreateDelegate(typeof(Func<string, string, int>), method);
我收到一个参数异常,说 "the target method cannot be bound to since its signature or security transparency is not compatible with the delegate type"(从瑞典语自由翻译)
怎么了?
IIRC "extend the parameters and treat the first as the target" 技巧仅适用于引用类型,例如 string
- 大概是因为此 instance 方法调用成为静态调用 address 第一个参数,而不是简单地 loading 这两个参数。你可以破解它 - 不是很优雅 - 通过:
var dm = new DynamicMethod(nameof(double.CompareTo), typeof(int),
new[] { typeof(double), typeof(double) });
var il = dm.GetILGenerator();
il.Emit(OpCodes.Ldarga_S, 0); // load "ref arg0"
il.Emit(OpCodes.Ldarg_1); // load "arg1"
il.Emit(OpCodes.Call, method); // call CompareTo
il.Emit(OpCodes.Ret);
var func = (Func<double, double, int>)dm.CreateDelegate(
typeof(Func<double, double, int>));
或者更简单地说,当然(尽管我怀疑这在一般情况下无济于事):
Func<double, double, int> func = (x,y) => x.CompareTo(y);
我正在尝试为 double.CompareTo 创建一个函数。
我是这样创建的:
var method = typeof(double).GetMethod("CompareTo", new Type[] { typeof(double) });
var func = (Func<double, double, int>)Delegate.CreateDelegate(typeof(Func<double, double, int>), method);
它适用于 string.CompareTo 像这样:
var method = typeof(string).GetMethod("CompareTo", new Type[] { typeof(string) });
var func = (Func<string, string, int>)Delegate.CreateDelegate(typeof(Func<string, string, int>), method);
我收到一个参数异常,说 "the target method cannot be bound to since its signature or security transparency is not compatible with the delegate type"(从瑞典语自由翻译)
怎么了?
IIRC "extend the parameters and treat the first as the target" 技巧仅适用于引用类型,例如 string
- 大概是因为此 instance 方法调用成为静态调用 address 第一个参数,而不是简单地 loading 这两个参数。你可以破解它 - 不是很优雅 - 通过:
var dm = new DynamicMethod(nameof(double.CompareTo), typeof(int),
new[] { typeof(double), typeof(double) });
var il = dm.GetILGenerator();
il.Emit(OpCodes.Ldarga_S, 0); // load "ref arg0"
il.Emit(OpCodes.Ldarg_1); // load "arg1"
il.Emit(OpCodes.Call, method); // call CompareTo
il.Emit(OpCodes.Ret);
var func = (Func<double, double, int>)dm.CreateDelegate(
typeof(Func<double, double, int>));
或者更简单地说,当然(尽管我怀疑这在一般情况下无济于事):
Func<double, double, int> func = (x,y) => x.CompareTo(y);