请看下面的代码。 问题发生在以下loc。 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;
}
答案 0 :(得分:1)
我通常使用的模式是is
运算符,它将告诉您的对象是否是特定类型。如果您已经知道要使用哪些对象
Object myObject
if(myObject is Obj1)
// do obj1 stuff
else if(myObject is Obj2)
// do stuff with obj2
我从来没有遇到过我需要操作超过少数几种不同类型并特别对待它们的地方,所以这就是我通常做的事情。
答案 1 :(得分:0)
您可以使用OfType<T>
扩展程序轻松获取列表中某种类型的所有对象:
lstObjectCollection.OfType<MyClassExample>()
如果类型仅在运行时已知,则可以执行以下操作:
lstObjectCollection.Where(o => o.GetType() == type)