小弟初学C#
请问如何取得集合中元素的类型
比如
string[] tstr;
MatchCollection mc;
如何取得tstr mc中元素的类型
不是tsrt mc的类型,是它们中的元素的类型
即"string" "Match"

解决方案 »

  1.   

    foreach(object obj in tstr)
     Console.WriteLine(obj.GetType())
      

  2.   

    是个问题,暂时没想到解决办法从感官上说,跟集合的名字是对应的
    xxxxCollection元素的类型就是xxxx
      

  3.   

    不太明白LS两位的
    GetType()只能Get到集合的类型,MS不能Get到元素的类型
      

  4.   

    for(int i =0 ;i<list.length ;++i)
    {
      ///////////
    }
    2. 
    foreach(intlist n in int.length)
    {
        .....
    }
      

  5.   

    我知道了!
    你说你是个初学者,但你这个问题很有深度,经过几天的研究,我终于找到方法了:        public Type GetElementType(Type t)
            {
                if (t.HasElementType)
                    return t.GetElementType();
                if (t.GetInterface("IEnumerable") != null)
                    return t.GetMethod("GetEnumerator").ReturnType.GetProperty("Current").PropertyType;
                throw new ApplicationException("类型\"" + t + "\"不是集合");
            }
    调用:
    Console.WriteLine(GetElementType(typeof(string[])));
    Console.WriteLine(GetElementType(typeof(List<int>)));
    Console.WriteLine(GetElementType(typeof(Dictionary<int,string>)));
    Console.WriteLine(GetElementType(typeof(MatchCollection)));最后一个会返回object,不是很理想,但VS自身也只能这样:
    foreach(var v in someMathCollection)
      v..//VS也只能推断出v是object所以我这个方法应经算是很完美了,你甚至可以使用不安全代码下的指针(楼主要是不懂不安全代码,就不要试这个了):Console.WriteLine(GetElementType(typeof(int*)));//能够正确的得到int
    我觉得我的回答可以得200分,可惜只有20分,呵呵
      

  6.   

    我知道了!
    你说你是个初学者,但你这个问题很有深度,经过几天的研究,我终于找到方法了:        public Type GetElementType(Type t)
            {
                if (t.HasElementType)
                    return t.GetElementType();
                if (t.GetInterface("IEnumerable") != null)
                    return t.GetMethod("GetEnumerator").ReturnType.GetProperty("Current").PropertyType;
                throw new ApplicationException("类型\"" + t + "\"不是集合");
            }
    调用:
    Console.WriteLine(GetElementType(typeof(string[])));
    Console.WriteLine(GetElementType(typeof(List<int>)));
    Console.WriteLine(GetElementType(typeof(Dictionary<int,string>)));
    Console.WriteLine(GetElementType(typeof(MatchCollection)));最后一个会返回object,不是很理想,但VS自身也只能这样:
    foreach(var v in someMathCollection)
      v..//VS也只能推断出v是object所以我这个方法应经算是很完美了,你甚至可以使用不安全代码下的指针(楼主要是不懂不安全代码,就不要试这个了):Console.WriteLine(GetElementType(typeof(int*)));//能够正确的得到int
    我觉得我的回答可以得200分,可惜只有20分,呵呵