【问题标题】:How to cast object at runtime, while getting type information at runtime如何在运行时转换对象,同时在运行时获取类型信息
【发布时间】:2012-12-11 15:33:30
【问题描述】:

请看下面的代码。 问题在以下位置。 MyClassExample obj2 = lstObjectCollection[0] as type;

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

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

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

【问题讨论】:

  • 检查是否对您有帮助:stackoverflow.com/questions/312858/…
  • 您的示例令人困惑。如果您不知道分配 obj2 的类型,您可以使用该引用做什么?换句话说,你想解决什么问题?
  • 我的意思是混淆- CreateDuplicateObject 是否相关?如果有,怎么做?

标签: c#


【解决方案1】:

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

Object myObject

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

我从来没有遇到过需要对多种不同类型进行操作并对其进行特殊处理的情况,所以这是我通常的做法。

【讨论】:

    【解决方案2】:

    您可以使用OfType&lt;T&gt;扩展方法轻松获取列表中某个类型的所有对象:

    lstObjectCollection.OfType<MyClassExample>()
    

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

    lstObjectCollection.Where(o => o.GetType() == type)
    

    【讨论】:

    • MyClassExample 类的类型在类型对象中。在运行时,我不确定哪个类将在类型对象中。将在运行时找到将要转换的对象的类型。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-20
    • 2010-09-23
    • 1970-01-01
    • 1970-01-01
    • 2011-09-20
    • 1970-01-01
    相关资源
    最近更新 更多