0

以下のコードをご覧ください。問題は次の場所にあります。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;
}
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 に答える