如何在模型上获取属性名称?

时间:2014-04-10 08:32:54

标签: c#

如何在我创建的模型上获取attibut的名称?

例如,对于这种情况,ID_HR,SURNAME,NAME 我试过了Get Getpertperties,但它没有工作

public class Person
{

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

}

我试过这个

 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);

                }

和这个

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

3 个答案:

答案 0 :(得分:1)

这是因为您声明的不是属性,而是简单的成员变量。 GetProperties不适用于成员变量。使用它来获取属性:

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; }
}

答案 1 :(得分:1)

您需要使用getset声明您的媒体资源,否则它只会是member variable。试试这样:

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; }
}

然后使用GetProperties方法。

答案 2 :(得分:0)

如果你上课VMS_Data就像这样

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

然后当你做

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

您尝试从FieldInfo获取类型。您需要使用FieldType来代替此

Type child = children[i].FieldType;