【发布时间】: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#