我搜索了一些关于类似问题的不同帖子,但似乎没有一个能解决我的特定问题(尽管我相信它们相距不远)。
下面的链接是最接近我的问题的版本
"Object does not match target type" when calling methods using string in C#
我的问题与链接中的问题之间的唯一区别是我调用的是通用方法。
当我打电话时,我收到错误消息“对象与目标类型不匹配”,但类型,我能判断的绝对匹配。 这是我重现问题的示例代码。
任何帮助将不胜感激
class Program
{
static void Main(string[] args)
{
var obj = new SerializeObject();
var serializer = new Serializer();
var serialiserType = serializer.GetType();
MethodInfo method = serialiserType.GetMethod("Deserialize");
if (method == null)
{
return;
}
var t = obj.GetType();
MethodInfo genericMethod = method.MakeGenericMethod(t);
var tmp = genericMethod.Invoke(obj, new object[] { "Test" }); //error here
}
}
public class Serializer
{
public T Deserialize<T>(string value) where T : new()
{
return new T();
}
}
public class SerializeObject
{
}
最佳答案
documentation声明第一个参数 obj
必须是您希望调用反射方法的实例:
obj Object
The object on which to invoke the method or constructor. If a method is static, this argument is ignored. If a constructor is static, this argument must be null or an instance of the class that defines the constructor.
因此,我会将调用更改为以下内容:
var tmp = genericMethod.Invoke(serializer, new object[] { "Test" });
关于c# - “Object does not match target type” 用反射调用泛型方法时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52429388/