开发者

Get Generic Container Type

I need to find out if a Type I'm working with is a Generic 'container', for example if I have a List<int> I need to check if I'm working with a List (I know how to get whether I'm working with an int), how would I do that? (I'm thinking Reflectio开发者_运维问答n). Another example, I have a class called StructContainer<T>, I need to find the word (name) 'StructContainer', I'm not too bothered with what 'T' is, using reflection I get StructContainer'1, would hate to have to do some string splitting etc /EDIT: Just to explain further, StructContainer<int> I need 'StructContainer', Tuple<int> I need 'Tuple', List<int> I need 'List' and so forth


Your first question can be achieved in multiple ways:

  1. Check whether your object implements IEnumerable<T>: yourObject is IEnumerable<int>. This only works if you know the type of the object in the container (int in this case)
  2. Use the same solution I described below, just change StructContainer to List.

As to your second question, you can do this:

var yourObject = new StructContainer<int>();
var yourType = yourObject.GetType();
if(yourType.IsGenericType &&
   yourType.GetGenericTypeDefinition() == typeof(StructContainer<>))
    // ...


string type = yourObject.GetType().Name.Split('`')[0];
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜