I have a class named BackUp
that contains a few properties. Let's say I have an existing instance of BackUp
with its properties initialized.
As I use reflection in the BackUp
class where I want to create an AgentActivator
object and I need to set its properties, the idea is to retrieve the properties from the BackUp
object.
The problem is to take PropertyInfo
object from the BackUp
object and set the matching property on the reflected object.
I am doing the following:
Assembly assembly = Assembly.LoadFile(localBackUp.AssemblyFileName);
Type currentClasstype = assembly.GetType(localBackUp.ClassName);
PropertyInfo[] properties = currentClasstype.GetProperties();
object classInstance = Activator.CreateInstance(localBackUp.AssemblyFileName,
localBackUp.ClassName);
string propName= null;
foreach(PropertyInfo prop in properties)
{
propName= prop.Name;
currentClasstype.GetProperty(propName).
SetValue(classInstance, findProperty(localBackUp, propNmae), null);
}
I need to find a way to implement the findProperty
Method. Its job is to get the string (property name) and return the matching value from the localBackUp
which holds property with the propName
.
From your code I assume that Type
of localBackup
and classInstance
is the same and thus are just initializing a new class instance with the same property values another class instance ( localBackup
) already has try
prop.GetSetMethod().Invoke (classInstance, new object[] { prop.GetGetMethod().Invoke(localBackUp, null) } );
One remark though:
IF my assumption is true then there are IMHO much better options to do what you are trying (for example by serializing and deserializing an instance)...
If your goal is clone the object, the best (I think) approach is described here: Deep cloning objects (as @Yahia mentioned serialize and deserialize). Quite important is that it returns deep copy , so original and new object don't share data between itself.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.