【发布时间】:2011-05-11 13:11:36
【问题描述】:
我有一个将通用列表转换为字符串的扩展方法。
public static string ConvertToString<T>(this IList<T> list)
{
StringBuilder sb = new StringBuilder();
foreach (T item in list)
{
sb.Append(item.ToString());
}
return sb.ToString();
}
我有一个对象类型的对象,它包含一个列表;该列表可以是List<string>、List<int>、List<ComplexType> 任何类型的列表。
有没有一种方法可以检测到这个对象是一个泛型列表并因此转换为该特定的泛型列表类型来调用ConvertToString 方法?
//ignore whats happening here
//just need to know its an object which is actually a list
object o = new List<int>() { 1, 2, 3, 4, 5 };
if (o is of type list)
{
string value = (cast o to generic type).ConvertToString();
}
【问题讨论】: