C#.net 4.0
我有一个功能
public static void CreateXMLOfCollection(ClassCollection ArraylstObject)
{
//Convert array list into List<> Then pass it for XML Creation:
Type classType = AlstObject[0].GetType(); // here is the problem..
List<classType > lst = ConvertArrayListToList <classType> (AlstObject);
}
public static List<T> ConvertArrayListToList<T>(BusinessObjectCollection collection)
{
//Code for conversion..
return lstconvertedArrayList;
}
在CreateXMLOfCollection
中我没有得到如何获取类的实例,假设我有一个类Person
然后我会写:
List<Person> lst = ConvertArrayListToList <Person> (AlstObject); //AlstObject is collection of array list of person class.
您是否可以建议从Person
ArraylstObject
类实例的通用方法
如果我这样做
string className = AlstObject[0].getType().Name; //it gives "Person"
答案 0 :(得分:1)
这样就可以了。
public static List<T> ConvertArrayListToList<T>(BusinessObjectCollection collection)
{
var list = new List<T>();
foreach(object obj in collection)
{
try
{
T newObj = (T)Convert.ChangeType(obj, typeof(T));
list.Add(newObj);
}
catch
{
}
}
return list;
}
这也将以相同的方式工作。
public static List<T> ConvertArrayListToList<T>(BusinessObjectCollection collection)
{
var list = new List<T>();
foreach(object obj in collection)
{
try
{
T newObj = (T)obj;
list.Add(newObj);
}
catch
{
}
}
return list;
}