Description:
If I have a class called person with a property of FirstName.
I can access the value like this:
Person.FirstName = "Mike"
Is there a way to access the Property like this:
Person["FirstName"] = "Mike" ?
Answer:
-
You can access values of object properties using the GetMemberValue(String) and SetMemberValue(String, Object) methods of the XPBaseObject class. Instead of hardcoding a property name, use the nameof(YourClassName.YourPropertyName) syntax.
However, this approach does not support nested property paths and indexed access. You should implement parsing of such complex paths yourself, as described in Get properties values from XPO Objects by Name. -
You can use the XPClassInfo and XPMemberInfo objects to write the code in such a manner:
C#XPClassInfo classInfo = s.GetClassInfo(typeof(B));
XPMemberInfo memberInfo = classInfo.GetMember("a");
la = new A(s);
memberInfo.SetValue(lb, la);
- You can extend your class with an index property:
C#public class MyClass: XPCustomObject {
public object this[string propertyName] {
get { return ClassInfo.GetMember(propertyName).GetValue(this); }
set { ClassInfo.GetMember(propertyName).SetValue(this, value); }
}
....
}
This will simplify the access to properties:
C#myObject["FirstName"] = "Mike";
Also, you can use reflection classes:
C#class MyClass: XPObject {
...
private PropertyInfo PropertyInfoByName(string name) {
Type type = this.GetType();
PropertyInfo info = type.GetProperty(name);
if (info == null)
throw new Exception(String.Format(
"A property called {0} can't be accessed for type {1}.",
name, type.FullName));
return info;
}
public object this[string name] {
get {
PropertyInfo info = PropertyInfoByName(name);
return info.GetValue(this, null);
}
set {
PropertyInfo info = PropertyInfoByName(name);
info.SetValue(this, value, null);
}
}
Note, that the performance of XPBaseObject.Get/SetMemberValue, XPMemberInfo.GetValue and XPMemberInfo.SetValue may be better than the performance of reflection classes (PropertyInfo, FieldInfo) because XPMemberInfo makes special accessors to properties by ILGenerator class.