I've searched a few different posts about a similar issue but none seem to solve my particular issue (though I believe they can't be far off).
The below link is the closest version to my problem
"Object does not match target type" when calling methods using string in C#
The only difference between my issue and the one in the link is that I am calling a generic method.
When I make my call I get the error "Object does not match target type” but the types, form what I can tell definitely match. Here is sample code for which I have reproduced my problem.
Any help would be appreciated
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
{
}
The documentation states that the first parameter obj
must be the instance you wish to call the reflected method on:
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.
As such, I would change the call to the following:
var tmp = genericMethod.Invoke(serializer, new object[] { "Test" });
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.