C#泛型列表<T>如何获取T的类型?

我正在做一个反思项目,现在被困了。如果我有一个可以容纳列表的“ myclass”对象,如果myclass.SomList属性为空,是否有人知道如何获取以下代码中的类型?


List<myclass>  myList  =  dataGenerator.getMyClasses();

lbxObjects.ItemsSource = myList; 

lbxObjects.SelectionChanged += lbxObjects_SelectionChanged;


private void lbxObjects_SelectionChanged(object sender, SelectionChangedEventArgs e)

        {

            Reflect();

        }

Private void Reflect()

{

foreach (PropertyInfo pi in lbxObjects.SelectedItem.GetType().GetProperties())

{

      switch (pi.PropertyType.Name.ToLower())

      {

       case "list`1":

           {           

            // This works if the List<T> contains one or more elements.

            Type tTemp = GetGenericType(pi.GetValue(lbxObjects.SelectedItem, null));


            // but how is it possible to get the Type if the value is null? 

            // I need to be able to create a new object of the type the generic list expect. 

            // Type type = pi.getType?? // how to get the Type of the class inside List<T>?

             break;

           }

      }

}

}

private Type GetGenericType(object obj)

        {

            if (obj != null)

            {

                Type t = obj.GetType();

                if (t.IsGenericType)

                {

                    Type[] at = t.GetGenericArguments();

                    t = at.First<Type>();

                } return t;

            }

            else

            {

                return null;

            }

        }


呼啦一阵风
浏览 3668回答 3
3回答

RISEBY

Type type = pi.PropertyType;if(type.IsGenericType && type.GetGenericTypeDefinition()&nbsp; &nbsp; &nbsp; &nbsp; == typeof(List<>)){&nbsp; &nbsp; Type itemType = type.GetGenericArguments()[0]; // use this...}通常,要支持any IList<T>,您需要检查接口:foreach (Type interfaceType in type.GetInterfaces()){&nbsp; &nbsp; if (interfaceType.IsGenericType &&&nbsp; &nbsp; &nbsp; &nbsp; interfaceType.GetGenericTypeDefinition()&nbsp; &nbsp; &nbsp; &nbsp; == typeof(IList<>))&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; Type itemType = type.GetGenericArguments()[0];&nbsp; &nbsp; &nbsp; &nbsp; // do something...&nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; }}

慕斯王

给定一个对象,我怀疑是某种的IList<>,我怎么能确定的东西它是一个IList<>?这是勇敢的解决方案。它假定您具有要测试的实际对象(而不是Type)。public static Type ListOfWhat(Object list){&nbsp; &nbsp; return ListOfWhat2((dynamic)list);}private static Type ListOfWhat2<T>(IList<T> list){&nbsp; &nbsp; return typeof(T);}用法示例:object value = new ObservableCollection<DateTime>();ListOfWhat(value).Dump();版画typeof(DateTime)

神不在的星期二

Marc的答案是我为此使用的方法,但是为了简单起见(以及更友好的API?),您可以在集合基类中定义一个属性,如果您具有以下属性:public abstract class CollectionBase<T> : IList<T>{&nbsp; &nbsp;...&nbsp; &nbsp;public Type ElementType&nbsp; &nbsp;{&nbsp; &nbsp; &nbsp; get&nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;return typeof(T);&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp;}}我发现这种方法很有用,并且对于任何泛型新手来说都很容易理解。
打开App,查看更多内容
随时随地看视频慕课网APP