Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

How do I call SomeObject.SomeGenericInstanceMethod<T>(T arg) ?

There are a few posts about calling generic methods, but not quite like this one. The problem is that the method argument parameter is constrained to the generic parameter.

I know that if the signature were instead

SomeObject.SomeGenericInstanceMethod<T>(string arg)

then I could get the MethodInfo with

typeof (SomeObject).GetMethod("SomeGenericInstanceMethod", new Type[]{typeof (string)}).MakeGenericMethod(typeof(GenericParameter))

So, How do I go about getting the MethodInfo when the regular arguments are of a generic type? Thanks!

Also, there may or may not be type constrains on the generic parameter.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
288 views
Welcome To Ask or Share your Answers For Others

1 Answer

You do it exactly the same way.

When you call MethodInfo.Invoke, you pass all the arguments in an object[] anyway, so it's not like you have to know the types at compile time.

Sample:

using System;
using System.Reflection;

class Test
{
    public static void Foo<T>(T item)
    {
        Console.WriteLine("{0}: {1}", typeof(T), item);
    }

    static void CallByReflection(string name, Type typeArg,
                                 object value)
    {
        // Just for simplicity, assume it's public etc
        MethodInfo method = typeof(Test).GetMethod(name);
        MethodInfo generic = method.MakeGenericMethod(typeArg);
        generic.Invoke(null, new object[] { value });
    }

    static void Main()
    {
        CallByReflection("Foo", typeof(object), "actually a string");
        CallByReflection("Foo", typeof(string), "still a string");
        // This would throw an exception
        // CallByReflection("Foo", typeof(int), "oops");
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...