1

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.

Otiel
  • 18,404
  • 16
  • 78
  • 126
aralele
  • 63
  • 1
  • 8
  • You'd better first fix all those typos… Then you can hope for someone to deciper your code. – Ondrej Tucny Nov 13 '11 at 10:48
  • Also, when you already know how to call `SetValue` you sure will figure out how to call `GetValue`. – Ondrej Tucny Nov 13 '11 at 10:49
  • I tried to fix the grammar without changing the meaning of your sentences. Not sure if I successed, so apologizes in advance if that's not the case. – Otiel Nov 13 '11 at 11:03
  • 1
    Since you are already showing GetProperty usage, I'm unclear where the problem is - can you clarify we're you are stuck? – Marc Gravell Nov 13 '11 at 11:06
  • 1
    How does `localBackup` store the property information? In a dictionary? – svick Nov 13 '11 at 11:52

2 Answers2

1

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)...

Yahia
  • 69,653
  • 9
  • 115
  • 144
0

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.

Community
  • 1
  • 1
Michał Powaga
  • 22,561
  • 8
  • 51
  • 62