简体   繁体   中英

C# Reflection with generics

I have been searching for this for some time but not gotten anywhere. I want to do the following:

Given a type say Dictionary<string,MyClass> and say its method ContainsKey(string) - at run time I want to be able to extract out the 'Generic signature' of this method. That is I want to get Boolean Dictionary<TKey,TValue>.ContainsKey(TKey) ( and not Boolean ContainsKey(string) )

I know that this is possible by doing the following

var untyped_methods = typeof(DictObject).GetGenericTypeDefition().GetMethods();
// and extract the method info corresponding to ContainsKey

However is is possible to get this information directly from the methods reflected from the actual type and not from the Generic types ? Meaning Can I get the generic definition from methods that have been obtained as follows :

var actual_typed_methods = typeof(DictObject).GetMethods()

In essence is it possible to get the " un-typed " method signatures from MethodInfo objects returned in the second snippet above directly (not via comparing the lists and figuring out)

Thanks

EDIT: Maybe this did what you wanted. Not sure if you were actually looking to Invoke or not.

If Invoking, then no (see below). If you just want the definition, then you can use typeof(Dictionary<,>) to get the raw generic definitions.


Unfortunately, no if you are wanting to Invoke .

Demonstration of why:

void Main()
{
    var genericDictionaryType = typeof(Dictionary<,>);
    var method = genericDictionaryType.GetMethod("ContainsKey");
    var dict = new Dictionary<string, string>();

    dict.Add("foo", "bar");
    Console.WriteLine("{0}", method.Invoke(dict, new[] { "foo" }));
}

Yields the following error:

Late bound operations cannot be performed on types or methods for which ContainsGenericParameters is true.

Sounds simple enough to fix. Just call method.MakeGenericMethod(typeof(string)); to get the actual typed MethodInfo object.

Unfortunately again, you cannot.

Boolean ContainsKey(TKey) is not a GenericMethodDefinition. MakeGenericMethod may only be called on a method for which MethodBase.IsGenericMethodDefinition is true.

Reason for this is because the method defined as bool ContainsKey(TKey) instead of bool ContainsKey<TKey>(TKey) .

You will need to get the ContainsKey method from the correct Dictionary<TK,TV> signature in order to use it.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM