Reputation: 4177
Is there any way to set the properties of the objects from string. For example I have "FullRowSelect=true" and "HoverSelection=true" statements as string for ListView property.
How to assign these property along with their values without using if-else or switch-case statments? Is there any SetProperty(propertyName,Value)
method or similar for this?
Upvotes: 1
Views: 3104
Reputation: 101150
First variant is to use reflection:
public class PropertyWrapper<T>
{
private Dictionary<string, MethodBase> _getters = new Dictionary<string, MethodBase>();
public PropertyWrapper()
{
foreach (var item in typeof(T).GetProperties())
{
if (!item.CanRead)
continue;
_getters.Add(item.Name, item.GetGetMethod());
}
}
public string GetValue(T instance, string name)
{
MethodBase getter;
if (_getters.TryGetValue(name, out getter))
return getter.Invoke(instance, null).ToString();
return string.Empty;
}
}
to get a property value:
var wrapper = new PropertyWrapper<MyObject>(); //keep it as a member variable in your form
var myObject = new MyObject{LastName = "Arne");
var value = wrapper.GetValue(myObject, "LastName");
You can also use Expression
class to access properties.
Upvotes: 1
Reputation: 6882
Try this:
PropertyInfo pinfo = this.myListView.GetType().GetProperty("FullRowSelect");
if (pinfo != null)
pinfo.SetValue(this.myListView, true, null);
Upvotes: 1
Reputation: 39620
You can use reflection to do this:
myObj.GetType().GetProperty("FullRowSelect").SetValue(myObj, true, null);
Upvotes: 2
Reputation: 43084
Try this:
private void setProperty(object containingObject, string propertyName, object newValue)
{
containingObject.GetType().InvokeMember(propertyName, BindingFlags.SetProperty, null, containingObject, new object[] { newValue });
}
Upvotes: 3
Reputation: 437434
This can be accomplished with reflection, for example look at this question.
Upvotes: 0
Reputation: 12849
You can look at Reflection. Its possible to find property and set its value thanks to this. But you need to parse your string yourself. And it may be problem geting valid value of correct type from string.
Upvotes: 0
Reputation: 9391
There isn't such a method, but you could write one using reflection.
Upvotes: 0
Reputation: 35679
You can do this with reflection, have a look at the PropertyInfo class's SetValue method
YourClass theObject = this;
PropertyInfo piInstance = typeof(YourClass).GetProperty("PropertyName");
piInstance.SetValue(theObject, "Value", null);
Upvotes: 1