开发者

is this possible in C# GetStringName(o.Property) or o.Property.GetPropertyStringName()? [duplicate]

This question already has answers here: 开发者_Python百科 Closed 10 years ago.

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();
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜