views:

250

answers:

1

Is there any way the .NET 4.0 (or earlier) reflection API to resolve a generic type parameter? See the two lines after my ArgumentException comment for my current attempt.

[TestMethod]
public void TestGenericParameterTokenResolution()
{
    Type genericParameter = typeof(List<>).GetGenericArguments()[0];
    Assert.IsTrue(genericParameter.IsGenericParameter);
    int metadataToken = genericParameter.MetadataToken;

    // make sure the metadata token is a GenericParam
    Assert.AreEqual(metadataToken & 0xFF000000, 0x2A000000);

    Module module = typeof(List<>).Module;
    // the following both throw an ArgumentException.
    Type resolvedParameter = module.ResolveType(metadataToken);
    resolvedParameter = (Type)module.ResolveMember(metadataToken);

    Assert.AreSame(genericParameter, resolvedParameter);
}
A: 

What about this overload?

kek444
That's used for something else. I don't currently have an example in C# code of its use - it's probably not what you think it is. `typeof(List<int>) != typeof(List<>).Module.Resolve(typeof(List<>).MetadataToken, new Type { typeof(int) }, null)`
280Z28
The internal representation of the base type of `KeyedCollection<TKey,TItem>` is a TypeSpec metadata token for `Collection<TItem>`, where `TItem` refers back to the corresponding generic parameter of `KeyedCollection`. To resolve that TypeSpec, you need to pass `typeof(KeyedCollection<,>).GetGenericArguments()` to `ResolveType`. However, I know of no way in C# to get that TypeSpec token to show you this in action.
280Z28
Yeah, I see.. I think I read somewhere a list of things Reflection can't do with metadata and I think this falls under that. Sounds interesting though. Did you ever take a look at the metadata unmanaged API?
kek444