Name of object within another object
I have a class called Prescriptions. It has properties that are other classes. So, for example, a property name of Fills would be from the PDInt class which has other properties about the value that I need.
If I want to set the value of the Fills property in the Prescription class it would be something like
Prescription p = new Prescription();
p.Fills开发者_运维知识库.Value = 33;
So now I want to take the name of the Fills property and stuff it in a the tag property in a winform control.
this.txtFills.Tag = p.Fills.GetType().Name;
However when I do this, I get the base class of the property, not the property name. So instead of getting "Fills", I get "PDInt".
How do I get the instantiated name of the property?
Thank you.
Below is an extension method that I use it when I wanna 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 as :
var name = p.Item(x=>x.Fills);
For detail about how method works see Expression Tree in .Net
Check this blogpost which is helpful : http://handcraftsman.wordpress.com/2008/11/11/how-to-get-c-property-names-without-magic-strings/
Do this you need to make USe of reflection feature of .net framework.
Something like this
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;
}
You can get you like as 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
}
精彩评论