To get the
property
of a class with the syntax
[ ]
Indexer
explained here
http://msdn.microsoft.com/en-us/library/6x16t2tx.aspx[
^] can be used.
Since, a
property
of the class is required to be returned the return type can be
PropertyInfo
class explained here
http://msdn.microsoft.com/en-us/library/system.reflection.propertyinfo.aspx[
^]
The
GetValue
and
SetValue
methods of
PropertyInfo
requires the
object
whose property value is required. In the present case since the
property
is of the
class
which returned it, it is redundant to again pass the instance of the class to
get
the value or
set
the value of the property.
Hence, a class
InstancePropertyInfo
is created as shown below:
void Main()
{
MyClass myclass = new MyClass();
myclass.Name="MyName";
InstancePropertyInfo pinfo = myclass["Name"];
Console.WriteLine (pinfo.GetValue());
myclass["Desc"].SetValue("Description---");
Console.WriteLine (myclass["Desc"].GetValue());
}
public class MyClass {
public InstancePropertyInfo this[string propertyName] {
get {
return
new InstancePropertyInfo (this, this.GetType().GetProperty(propertyName,
BindingFlags.Instance | BindingFlags.Public));
}
}
public string Name { get; set; }
public string Desc { get; set; }
}
public class InstancePropertyInfo {
PropertyInfo propertyInfo;
object target;
public InstancePropertyInfo (object target, PropertyInfo propertyInfo) {
this.target = target;
this.propertyInfo=propertyInfo;
}
public object GetValue () {
return propertyInfo.GetValue(target, null);
}
public void SetValue(object value) {
propertyInfo.SetValue(target,value,null);
}
}