Reflection: a method with a common parameter is called

I'm all

I have some problems with calling a method with reflection.

Method sign

public T Create<T, TK>(TK parent, T newItem, bool updateStatistics = true, bool silent = false)
        where T : class
        where TK : class;
    public T Create<T, TK>(TK parent, string newName, Language language = null, bool updateStatistics = true, bool silent = false)
        where T : class
        where TK : class;

I want to use the second overload.

My code

typeof(ObjectType).GetMethod("Create")
            .MakeGenericMethod(new Type[] { typeof(Item), typeof(TKparent) })
            .Invoke(_objectInstance, new object[] { parent, name, _language, true, false });

where Item is a class, TKparent is a type variable, and parent is an instance of TKparent.

I get a System.Reflection.AmbiguousMatchException.

I think the problem is with generics

I also tried this:

typeof(ObjectType).GetMethod("Create", new Type[] { typeof(TKparent), typeof(string), typeof(Globalization.Language), typeof(bool), typeof(bool) })
            .MakeGenericMethod(new Type[] { typeof(Item), typeof(Tparent) })
            .Invoke(_objectInstance, new object[] { parent, name, _language, true, false });

but in this case I get a System.NullReferenceException (method not found)

Can someone help with this, I'm angry!

Thank you

+4
source share
1 answer

, GetMethod , , . GetMethod, , , , .

GetMethods , :

var methods = typeof(ObjectType).GetMethods();

var method = methods.Single(mi => mi.Name=="Create" && mi.GetParameters().Count()==5);

method.MakeGenericMethod(new Type[] { typeof(Item), typeof(TKparent) })
      .Invoke(_objectInstance, new object[] { parent, name, _language, true, false });

, , , , , .

+2

All Articles