c# - “Object does not match target type” 用反射调用泛型方法时

标签 c# generics reflection

我搜索了一些关于类似问题的不同帖子,但似乎没有一个能解决我的特定问题(尽管我相信它们相距不远)。

下面的链接是最接近我的问题的版本

"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/

相关文章:

java - Bean 验证应用于接口(interface)类型

java - 获取java项目中带有特定注解的所有类

c# - XNA - 如何更改绘制字符串列表的方向

c# - 带有本地 SQL Server CE DLL 的 Entity Framework 代码优先 "ADO.NET provider not found"

c# - 启动多个线程时 Silverlight 应用程序没有响应

Java类型参数隐藏了泛型类型?

c# - WPF MVVM 模式中的关注点分离

Java:如何将 List<?> 转换为 Map<String,?>

c# - 通过传递名称获取和设置字段值

反射(reflect)类型时,Swift Mirror Children集合为空