如何从Class类型或字符串形式获取类的Class Instance

时间:2014-12-09 08:38:28

标签: c# .net generics type-conversion

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"

1 个答案:

答案 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;
}