Coco wrote:
I am wondering if this can be done.
Well i have a class that take any object, and the class will get string from
text file which is value need to be retrieved from this object. For example
the property called Name of the class Proposal. what i need is my class to be
able to read the string "Proposal.Name" and get the value Name from the
object without knowing the object Proposal.
Is there a way for this to be done?
I think that a little bit of reflection would do the trick. A complete
sample follows:
class Proposal
{
public string Name
{
get { return "Value of Proposal.Name"; }
}
}
class ReflectionReader
{
public object ReadPropertyValue(object o, string propertyName)
{
object result = null;
PropertyInfo propInfo =
o.GetType().GetProperty(propertyName);
if(propInfo != null)
{
result = propInfo.GetValue(o, null);
}
return result;
}
}
class Program
{
static void Main()
{
Console.WriteLine
(
new ReflectionReader().
ReadPropertyValue(new Proposal(), "Name")
);
}
}
Best regards!
Marcin