开发者

Get property name from class [duplicate]

开发者 https://www.devze.com 2022-12-29 05:59 出处:网络
This question already has answers here: 开发者_StackOverflow How to get name of a class property? (6 answers)
This question already has answers here: 开发者_StackOverflow How to get name of a class property? (6 answers) Closed 9 years ago.

I need property name in my app and I use next code to get it

string PropertyName =SomeClass.GetType().GetProperty("Category").Name;

But I think that is bad idea. Because I use web service classes and I dont know when property names can be changed. This code give me exception only in runtime. But if I write something like this SomeClassInstance.Property.GetProperyName i get exception in moment of compilation and repair this problem. Is it possible to get property name dynamically?


There is a very neat solution here: Workaround for lack of 'nameof' operator in C# for type-safe databinding?


 Expression<Func<string>> expression = () => Sample.Foo;
 MemberExpression body = (MemberExpression)expression.Body;
 string name = body.Member.Name;

Where Sample.Foo is your property So that would be SomeClass.Category.Name

0

精彩评论

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