我有一个引用包含多个重载实例方法的第 3 方 C# 程序集的项目。我想在我的代码中通过泛型调用这些方法之一,调用参数类型与泛型类型匹配的实例方法:
void GetVal<T>(ref T val)
{
VendorLib v = new VendorLib();
v.GetVal(ref val);
}
// error CS1503: Argument 1: cannot convert from 'ref T' to 'ref bool'
我最接近的是通过使用动态变量,但这会导致运行时异常,因为参数 d 解析为 bool,即使泛型的类型是 ulong,从而绑定(bind)了不正确的方法:
class MyClass
{
void Caller()
{
ulong val = 0;
this.GetValue<ulong>(ref val);
}
void GetValue<T>(ref T val)
{
dynamic d = val;
GetValDynamic(ref d);
}
void GetValDynamic(ref dynamic val)
{
VendorLib v = new VendorLib();
v.GetVal(ref val);
}
}
异常: 结果消息:Microsoft.CSharp.RuntimeBinder.RuntimeBinderException:“VendorLib.GetVal(ref bool)”的最佳重载方法匹配有一些无效参数
供应商库包含多个 GetVal 重载,其中 GetVal(ref bool)
是一个,GetVal(ref ulong)
是另一个。
为什么没有绑定(bind)正确的方法?
谢谢!
最佳答案
如果您不想检查 typeof(T) 并手动调用相应的方法,那么反射可以工作。像这样的……
public class MyVendorLibWrapper
{
private readonly VendorLib vendorLib;
public MyVendorLibWrapper()
{
this.vendorLib = new VendorLib();
}
public T GetValue<T>()
{
MethodInfo method = typeof(VendorLib)
.GetMethod("GetVal", new Type[] { typeof(T).MakeByRefType() });
object[] arguments = new object[] { default(T) };
method.Invoke(this.vendorLib, arguments);
return (T)arguments[0];
}
}
然后调用这样的东西...
MyVendorLibWrapper wrapper = new MyVendorLibWrapper();
int x = wrapper.GetValue<int>();
关于C#:从泛型调用外部程序集中的重载方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30361827/