开发者

dissecting a generic type

Suppose t is variable of type System.Type with the value

System.Collections.Generic.Diction开发者_如何学JAVAary`2[System.String,System.Int32]

Is there a method I can call on t such that it will return:

System.Collections.Generic.Dictionary

Otherwise, I'm thinking of calling .ToString() and using a regex (yuck)


There is no System.Collections.Generic.Dictionary. But you can get System.Collections.Generic.Dictionary`2 (i.e. the equivalent of typeof(Dictionary<,>)) by calling

t.GetGenericTypeDefinition()


Expanding on Timwi's and Vilx-'s answers, you might write a method to do something like this:

// Omitted null checking, type validation, etc. for brevity
static string GetNonGenericTypeName(Type genericType)
{
    Type baseType = genericType.GetGenericTypeDefinition();

    // This is PROBABLY fine since the ` character is not allowed in C# for one of
    // your own types.
    int stopIndex = baseType.FullName.IndexOf('`');

    return baseType.FullName.Substring(0, stopIndex);
}

Addendum: The above method (even aside from its lack of robustness from not validating input) suffers from a limitation that may or may not be significant, depending on the scope in which it would hypothetically be used: it assumes that the backtick character (`) would only occur in a class name if it were put there by the C# compiler; in other words, it assumes that any class it inspects is either from the BCL (which I don't believe includes any types with backticks in their names, aside from the generic ones of course) or written in C#, the "normal" way (i.e., not using some dynamic type definition library, for example).

It may well work for VB.NET and other .NET languages as well, but I'm less familiar with the naming rules of those languages so I can't currently say for sure.

If you were only using this method in your own internal library then obviously you would have control over whether or not the potential presence of backticks in a non-generic class name were realistic or even possible. If it were in a public library then it would be susceptible to returning inaccurate results for what I'll call more "exotic" but perfectly legal CLR types.


You can call the GetGenericTypeDefinition() method which will yield the "generic" type. That will still have the `2 appended. That's because that is the real type name to which it is compiled (the 2 is the count of generic parameters). From there I think you have little choice but to use string manipulation.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜