I am not sure if this is possible but I want to iterate through a class and set a field member property without referring to the field object explicitly:
public class Employee
{
public Person _person = new Person();
public void DynamicallySetPersonProperty()
{
MemberInfo[] members = this.GetType().GetMembers();
foreach (MemberInfo member in members.Where(a => a.Name == "_person"))
//get the _person field
{
Type type = member.GetType();
PropertyInfo prop = type.GetProperty("Name"); //good, this works, now to set a value for it
//this line does not work - the error is "property set method not found"
prop.SetValue(member, "new name", null);
}
}
}
public class Person
{
public string Name { get; set; }
}
In the answer that I marked as the answer you need to add:
public static bool IsNullOrEmpty(this string source)
{
return (source == null || source.Length > 0) ? true : false;
}
You a trying to perform
SetValue()
on the propertyName
of the variablemember
that is a MemberInfo object and this proeprty is read only.Note you do not need to iterate over all memebers and you do not need to get the field
_person
with reflection as it is defined in the same class as the methodDynamicallySetPersonProperty()
.So the code shoul read like this.
The first line will fail if
_person
is null. So you can use reflectiopn to get the type of the field.But now accessing this property will still fail if
_person
is null.Here's a complete working example:
EDIT: added a looping variant so you could see how to loop through property info objects.
try this:
usage example:
Have a look on this CodeProject article related to what you are trying to do
http://www.codeproject.com/KB/cs/fast_dynamic_properties.aspx
With the following Extension methods that I have created, you can set or get any property value even if they are nested
GetPropertyValue(customObject, "Property.Nested.Child.Name");
or set
SetPropertyValue(customObject, "Property.Nested.Child.Name", "my custom name");
And here are a couple of tests for it
Hope you find it useful.