简体   繁体   中英

How to get the attribute name on a model?

How can i get the attibut's name on a model that i have created ?

For example for this case ID_HR, SURNAME, NAME I tried whit GetProperties but it doesn't work

public class Person
{

    public string ID_HR;
    public string SURNAME;
    public string NAME;
    public string GENDER;
    public string N_GENDER;
    public DateTime? DT_BIRTH;

}

I TRIED THIS

 Type parent = typeof(VSM_Data);
            FieldInfo[] children = parent.GetFields();

            for (int i = 0; i < children.Length; i++)
            {

                Type child = children[i].GetType();

                var columnnamesChild = from t in child.GetProperties() select t.Name;
                foreach (var item in columnnamesChild)
                {
                    DragAndDrop FundDragAndDrop = new DragAndDrop();
                    FundDragAndDrop.TITLE = item;
                    FundDragAndDrop.adresse = "{{PERSON." + children[i].Name.ToUpper() + "." + item.ToUpper() + "}}";
                    FundList.Add(FundDragAndDrop);

                }

AND THIS

FieldInfo[] myPropertyInfo = children[i].GetType().GetFields(BindingFlags.Public);

                for (int a = 0; a < myPropertyInfo.Length; a++)
                {
                    DragAndDrop FundDragAndDrop = new DragAndDrop();
                    FundDragAndDrop.TITLE = myPropertyInfo.ToString();
                    FundDragAndDrop.adresse = "{{PERSON." + children[i].Name.ToUpper() + "." + myPropertyInfo.ToString().ToUpper() + "}}";
                    FundList.Add(FundDragAndDrop);
                }

It's because what you've declared are not properties, but simple member variables. GetProperties does not work with member variables. Use this to get properties:

public class Person
{

    public string ID_HR { get; set; }
    public string SURNAME { get; set; }
    public string NAME { get; set; }
    public string GENDER { get; set; }
    public string N_GENDER { get; set; }
    public DateTime? DT_BIRTH { get; set; }
}

You need to declare your properties using get and set else it would be a member variable only. Try like this:

public class Person
{

    public string ID_HR { get; set; }
    public string SURNAME { get; set; }
    public string NAME { get; set; }
    public string GENDER { get; set; }
    public string N_GENDER { get; set; }
    public DateTime? DT_BIRTH { get; set; }
}

And then use the GetProperties method.

if you class VMS_Data something like this

class VMS_Data{
    ....
    Person p;
    Country c;
    ....
}

then when you do

Type child = children[i].GetType();

you try get type from FieldInfo . You need use FieldType instead like this

Type child = children[i].FieldType;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM