Set Reflection Property object without knowing the property name & value - c#

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.

Related

Creating a specific type of object chosen from a set of types obtained through reflection

I'm essentially coding an interface for a user to create instances of different classes. I'm using winforms so that if the code says the class has a property of type int, it provides a numbox, a check box for bool, etc. The form is generated at runtime and the controls shown depends on the number and type of the properties in the class being reflected upon.
I need to take the values the user inputs and create an object with the properties set to those values. The issue is that the number and types of the properties is different for each object. What I'd like is some way to do the following:
Object o = new Object(property1, property2)
Where Object would be replaced by whatever class is currently being used and the parameters are replaced with the values from the winform controls in the appropriate quantity.
The type that the class could be is limited to a finite list, and each class has a constructor in the style above. All classes have at least one property to set.
List<object> parms = new List<object>();
parms.Add(property1);
parms.Add(property2);
ObjectHandle objHandle = Activator.CreateInstance("assemblyName", "className", false, null, null, parms.ToArray(), null, null );
object workingObject = objHandle.Unwrap();
Replace "assemblyName" with your assembly's name and "className" with the fully-qualified name of your class.
This should give you the flexability to create an instance of any class with any number of constructor parameters.
from what i understand,
you need to have a factory class that will create and assign the properties
Following info may help.
to the factory class method you need to pass the following info
type of class/control needed ( as you mentioned int or bool, any thing is fine as long as your factory class understands this logic)
i.e it can create the control needed either by reflection or by simply instantiating the class
for passing the properties info i suggest to have a dictionary of type string,object
.string will store the property name as key and Object as its value
for assigning the properties values, you loop through this dictionary
and assign values using reflection as shown in the below sample
Type type = control.GetType();
PropertyInfo prop = type.GetProperty("propertyName");
prop.SetValue (control,propertyValue, null);
if my understanding is not right, please add more info on your question in the comments

Get Leaf Property Value Out Of Object's Tree Graph

I am stuck with PropertyInfo, big time. Basically it a tiny issue though idk where to start solving it. I dont usually use reflection but I need it now.
I have an object which has a property of type MyClass and MyClass futhermore holds another property. I want that last one. How do I get it?
Take a look at this:
obj.myClass.Attribute
How do I get that Attribute property by using PropertyInfo?
Use PropertyInfo.GetValue(Object):
Type type = obj.myClass.GetType();
PropertyInfo prop = type.GetProperty("Attribute");
object value = prop.GetValue(obj.myClass);

Access all properties of an unknown type

On my WinForm, I want to show each Property (as a label) and its value at run time depending on the type of the object. Something like this:
public void ShowDetails(object anyType)
{
// Generate label per property and show value of the property against a label.
}
How can I achieve this? There are more than 100 classes having different properties.
I am using C# 4.0.
You use reflection.
PropertyInfo[] properties = obj.GetType().GetProperties();
foreach (PropertyInfo property in properties)
{
object propertyValue = property.GetValue(obj, null);
}
That should be enough to get you started.
You can also get lots of other information out of the PropertyInfo such as the name of the property, the type, the accessibility, and so on. Note that it's possible (but very uncommon) to have a property without a getter, so you may want to check for that first. You also may want to only get public properties, rather than all properties. You also may want to check if the property is an indexer, as it will need a non-null value for the second parameter of GetValue. Oh, and you will also get static properties returned; you may or may not want those as well.
Use System.Reflection.PropertyInfo . You can loop through all properties (and sub-properties)
MSDN link
You can easily store the properties and their values in a dictionary
Dictionary<string,object> properties = anyType.GetType()
.GetProperties()
.ToDictionary(p=>p.Name,p=>p.GetValue(anyType,null));
I'd read up on Reflection. It will allow you to access the property names and values of class member at runtime.

How to set a value when the name of the value isn't known until runtime?

I am trying to set the properties of one object to be the same as the properties of another object. Here the code so far:
private T SetObjectAttributes<T> (dynamic fromO, T toO)
{
foreach (var prop in fromO.GetType().GetProperties())
{
toO[prop] = fromO[prop];
}
return toO;
}
The syntax here is incorrect:
toDbObject[prop] = fromObject[prop];
Basically, I am trying to set a property but the property name isn't known until run time. So my question is how to assign the value of the property at runtime.
You have to use the methods GetValue( object sourceObject) respectively SetValue( object target, object value ) of the PropertyInfo instance of the property.
You want to use PropertyInfo.SetValue to actually set the value. Also I hope you're caching those PropertyInfo instances - because it's going to really slow otherwise.
You should also look at ExpandoObject or some other options.
What exactly are you trying to do? Perhaps there's an altogether better way.

Dynamically parsing through nested classes for values and attributes

I have several models that includes nested classes and lists. Many of the class members have attributes that I also have to read in.
I'm looking for a dynamic way (possibly through Linq or Reflection) to retrieve the values and attributes of all generic objects within the specified model.
Any suggestions are welcome.
Edit:
Using the ObjectManager as per x0r's suggestion, I can see all of the data. The remaining part of this issue requires member annotation. Is there some way to copy over the PropertyInfo of each class member?
ObjectWalker objectWalker = new ObjectWalker(objectToValidate);
foreach (Object o in objectWalker)
{
if (isGeneric(o.GetType()))
{
PropertyInfo property = o.GetType().GetProperty(o); // <-- This does not work... Need to obtain annotations somehow
object[] Attributes = property.GetCustomAttributes(typeof(Attribute), true);
foreach (Attribute attribute in Attributes)
{
// Annotations processing goes here
}
}
}
Have a look at the ObjectWalker
It helps you to parse an object graph and visit all unique elements.
As you can see it stores only a stack of objects and Current returns an Object.
You could modify this so the Walker would save a class that contains all the data you need for each property (Like a propertyinfo object or a list of attributes).

Categories