日期:2014-05-20 浏览次数:20644 次
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);
}
}