Possible Duplicate:
How do I get the name of a property from a property in C# (2.0)
I need some method that is going to get the property's string name, I don't know if this is possible in C#, is it ?
Using expression trees in C# 3 and .NET 3.5 you can do something close:
GetStringName(() => o.Property)
or you can use anonymous types and reflection:
GetStringName(new { o.Property })
but both are kinda hacky. (I have a blog post with an example of the latter, admittedly for a slightly different purpose, but it demonstrates the general idea.) If you could tell us more about why you need to know this, we may be able to advise you better.
If you are wanting to get all the property names as an array of strings you can do this:
Type myClassType = myClass.GetType(); //get your class type
PropertyInfo[] myClassProps = myClassType.GetProperties();
You can then loop through them
string namesAndValues;
foreach(PropertyInfo prop in myClassProps){
namesAndValues += "Property Name: " + prop.Name + ", Value: " + prop.GetValue(myClass, null).ToString();
}
精彩评论