有一个方法A返回一个List<T>对象,在另一个方法B中接收,方法B中不能直接得到List<T>中T的类型,但却得遍历这个List<T>对象
问题:
能不能在B中通过反射获得T的对象类型?据说这是不可以的,因为在编绎期间T只作为一个占位符,在运行期间由具体类型替换。但如果这样的话,怎么遍历这个返回的List<T>对象?自带的DropDownList的DataSource可以为设定为List<T>,它这个应该也是遍历这个数据源,然后绑定的吧。
------解决方案--------------------------------------------------------
------解决方案--------------------------------------------------------
- C# code
class Sample{ void SomeMethodCore<T>(List<T> list) { // 这个地方你喜欢作什么就作什么,并且知道T的具体类型 foreach(T item in list) { Console.WriteLine(item); } } // 使用时,调用这个方法 void SomeMethod(object itShouldBeAList) { if (itShouldBeAList == null) throw new ArgumentNullException("itShouldBeAList"); if (!itShouldBeAList.GetType().IsGenericType) throw new ArgumentException("itShouldBeAList is not a List<T>"); if (itShouldBeAList.GetType().GetGenericTypeDefinition() != typeof(List<>)) throw new ArgumentException("itShouldBeAList is not a List<T>"); typeof(Sample).GetMethod("SomeMethodCore", BindingFlags.Instance | BindingFlags.NonPublic).MakeGenericMethod(itShouldBeAList.GetType().GetGenericArguments()).Invoke(this, new object[] { itShouldBeAList }); } // 一个模拟的调用 void Caller() { object list = new List<int>{1,2,3}; SomeMethod(list); }}