Getting class property value from string

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hi,

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?
 
Maybe you can use XML to represent your object text value. So, Using
XML serialization or XML API to parse XML string will be a easy job.

plz refer to System.Xml or System.Xml.Serialization namespace. Good
luck.

Sincerely,
simida

Coco 写é“:
 
Coco said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top