0

请看下面的代码。问题在以下位置。MyClassExample obj2 = lstObjectCollection[0] 作为类型;

我想将列表对象类型转换为它的类型。但是类型将在运行时给出。

我们如何转换一个对象,在运行时知道它的类型?

class RTTIClass
{
    public void creatClass()
    {
        // Orignal object
        MyClassExample obj1 = new MyClassExample {NUMBER1 =5 };

        // Saving type of original object.
        Type type = typeof(MyClassExample);

        // Creating a list.
        List<object> lstObjectCollection = new List<object>();

        // Saving new object to list.
        lstObjectCollection.Add(CreateDuplicateObject(obj1));

        // Trying to cast saved object to its type.. But i want to check its RTTI with type and not by tightly coupled classname.
        // How can we achive this.
        MyClassExample obj2 = lstObjectCollection[0] as type;           
    }


    public object CreateDuplicateObject(object originalObject)
    {
        //create new instance of the object
        object newObject = Activator.CreateInstance(originalObject.GetType());

        //get list of all properties
        var properties = originalObject.GetType().GetProperties();

        //loop through each property
        foreach (var property in properties)
        {
            //set the value for property
            property.SetValue(newObject, property.GetValue(originalObject, null), null);
        }


        //get list of all fields
        var fields = originalObject.GetType().GetFields();

        //loop through each field
        foreach (var field in fields)
        {
            //set the value for field
            field.SetValue(newObject, field.GetValue(originalObject));
        }

        // return the newly created object with all the properties and fields values copied from original object
        return newObject;
    } 

}


class MyClassExample
{

    public int NUMBER1 {get; set;}
    public int NUMBER2{get; set;}
    public int number3;
    public int number4;
}
4

2 回答 2

1

我通常使用的模式是is运算符,它将判断您的对象是否是特定类型。如果您已经有点知道您将使用哪些对象,这将起作用

Object myObject

if(myObject is Obj1)
    // do obj1 stuff
else if(myObject is Obj2)
    // do stuff with obj2

我从来没有遇到过这样的情况,我必须对多种不同的类型进行操作并特别对待它们,所以这就是我通常做的事情。

于 2012-12-11T15:38:41.477 回答
0

OfType<T>您可以使用扩展方法轻松获取列表中某种类型的所有对象:

lstObjectCollection.OfType<MyClassExample>()

如果类型仅在运行时已知,您可以这样做:

lstObjectCollection.Where(o => o.GetType() == type)
于 2012-12-11T15:38:53.407 回答