The name of the object inside another object

I have a class called Recipes. It has properties that are other classes. So, for example, the name of the Fills property will be from the PDInt class, which has other properties about what I need.

If I want to set the value of the Fills property in the Prescription class, it will be something like

Prescription p = new Prescription(); p.Fills.Value = 33;

So now I want to take the name of the Fills property and add it to the tag property in the winform control.

 this.txtFills.Tag = p.Fills.GetType().Name; 

However, when I do this, I get the base class of the property, not the name of the property. So instead of getting "Fillings", I get "PDInt".

How to get the instance name of a property?

Thanks.

+4
source share
3 answers

Below is the extension method that I use when I want to work like you:

 public static class ModelHelper { public static string Item<T>(this T obj, Expression<Func<T, object>> expression) { if (expression.Body is MemberExpression) { return ((MemberExpression)(expression.Body)).Member.Name; } if (expression.Body is UnaryExpression) { return ((MemberExpression)((UnaryExpression)(expression.Body)).Operand) .Member.Name; } throw new InvalidOperationException(); } } 

use it like:

 var name = p.Item(x=>x.Fills); 

For more details on how the method works, see .Net Expression Tree

+7
source

Check out this blog post which is helpful: http://handcraftsman.wordpress.com/2008/11/11/how-to-get-c-property-names-without-magic-strings/

Do this so that you can use the reflection function of the .net framework.

Something like that

 Type type = test.GetType(); PropertyInfo[] propInfos = type.GetProperties(); for (int i = 0; i < propInfos.Length; i++) { PropertyInfo pi = (PropertyInfo)propInfos.GetValue(i); string propName = pi.Name; } 
+1
source

Can you tell you about this? ↓

 public class Prescription { public PDInt Fills; } public class PDInt { public int Value; } Prescription p = new Prescription(); foreach(var x in p.GetType().GetFields()) { // var type = x.GetType(); // PDInt or X //Fills } 
0
source

All Articles