当前位置: 代码迷 >> ASP.NET >> 关于List<T>的有关问题
  详细解决方案

关于List<T>的有关问题

热度:1012   发布时间:2013-02-26 00:00:00.0
关于List<T>的问题
有一个方法A返回一个List<T>对象,在另一个方法B中接收,方法B中不能直接得到List<T>中T的类型,但却得遍历这个List<T>对象
问题:
能不能在B中通过反射获得T的对象类型?据说这是不可以的,因为在编绎期间T只作为一个占位符,在运行期间由具体类型替换。但如果这样的话,怎么遍历这个返回的List<T>对象?自带的DropDownList的DataSource可以为设定为List<T>,它这个应该也是遍历这个数据源,然后绑定的吧。


------解决方案--------------------------------------------------------
探讨
@oyiboy
关于T,就可以用反射来处理了。
但是这个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);  }}
  相关解决方案