lundi 6 mars 2023

C# reflection "Object does not match target type." when calling a method

I have the following code in a factory:

private readonly Type? ModelType;

public object Resolve()
    {
        if (ModelType != null)
        {
            var service = Activator.CreateInstance(ModelType);
            if (service != null)
            {
                var inf = service.GetType().GetInterfaces().FirstOrDefault();
                if (inf != null)
                {
                    MethodInfo? method = inf.GetMethod("LoadParameters");
                    if (method != null)
                    {
                        method.Invoke(inf, null);
                    }

                    return inf;
                }
            }
            throw new ArgumentOutOfRangeException($"Service must extend IBackendParamService<>!");
        }
        else
        {
            throw new ArgumentOutOfRangeException($"Type not found!");
        }
    }

Method invocation method.Invoke(inf, null); returns an exception with the message "Object does not match target type."

I don't understand why. The variable inf is the variable where I found the method. Any help would be appreciated!





Aucun commentaire:

Enregistrer un commentaire