By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
434,969 Members | 2,422 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 434,969 IT Pros & Developers. It's quick & easy.

Getting class property value from string

P: n/a
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?
Aug 1 '06 #1
Share this Question
Share on Google+
2 Replies


P: n/a
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 写道:
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?
Aug 1 '06 #2

P: n/a
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
Aug 1 '06 #3

This discussion thread is closed

Replies have been disabled for this discussion.