Hi, I have following problem:
(warning, quite long post with lots of code)
I have an object of a known type
like this.
class MyClass {
public int Property1;
public string Property2;
}
MyClass myClassObject;
object myObject = myClassObject;
of course I can do the reverse operation
MyClass myClassObject2 = (MyClass) myObject;
I have the string name of the property
string propertyName = "Property1";
I want to get the value from the object that is equivalent of:
object propertyValue = myClassObject.Property1
but using the string propertyName, and packaged or unpackaged object.
The only way I can think of is to do something as ugly as:
IGetAble {
object Get(string propertyName);
}
MyClass : IGetAble
{
public int Property1;
public string Property2;
object Get(string propertyName) {
object retValue;
switch (propertyName) {
case "Property1":
retValue = this.Property1;
break;
case "Property2":
retValue = this.Property2;
break;
default:
throw new ArgumentException("no such property");
}
return retValue;
}
}
and then
IGetAble instance = (IGetAble) myObject;
object propertyValue = instance.Get("Property1");
but this is UGLY!! it forces me to implement this method in each and every
class with this monstrous switch. The surely should be something in
reflection assembly that allow getting object instance property value by
type, name and instance.
Anyone know how to do it?
thanks
CUIN Kaczy