[英]How to get all Property name only in a Class
如何獲取以下類的所有屬性:
public class Employee
{
int employeeID;
string lastName; // should be (20) chars only
string firstName; // should be (10) chars only
string title; // should be (30) chars only
string address; // should be (60) chars only
string city; // should be (15) chars only
string region; // should be (15) chars only
string postalCode; // should be (10) chars only
string country; // should be (15) chars only
string extension; // should be (4) chars only
string homePhone;
public int EmployeeID
{
get
{
return employeeID;
}
set
{
employeeID = value;
}
}
public string LastName
{
get
{
return lastName;
}
set
{
lastName = value;
}
}
public string FirstName
{
get
{
return firstName;
}
set
{
firstName = value;
}
}
public string Title
{
get
{
return title;
}
set
{
title = value;
}
}
public string Address
{
get
{
return address;
}
set
{
address = value;
}
}
public string City
{
get
{
return city;
}
set
{
city = value;
}
}
public string Region
{
get
{
return region;
}
set
{
region = value;
}
}
public string PostalCode
{
get
{
return postalCode;
}
set
{
postalCode = value;
}
}
public string Country
{
get
{
return country;
}
set
{
country = value;
}
}
public string Extension
{
get
{
return extension;
}
set
{
extension = value;
}
}
public string HomePhone
{
get { return homePhone; }
set { homePhone = value; }
}
}
我嘗試使用Reflection / PropertyInfo,但有一個小問題,數據類型包含在列表中:
public PropertyInfo[] getPropertyInfo()
{
PropertyInfo[] propertyInfos;
propertyInfos = typeof(Employee).GetProperties();
return propertyInfos;
}
先感謝您。
您的方法為每個屬性返回一個PropertyInfo
數據結構,其中包括諸如屬性名稱,屬性返回類型等信息。如果只需要名稱,請訪問Name
屬性 。
要將PropertyInfo
的數組映射到屬性名稱的集合,可以使用LINQ Select
擴展方法:
var propertyNames = getPropertyInfo().Select(p => p.Name).ToList();
PS:您可能考慮使用自動實現的屬性來減少類中的代碼量:
...
public string LastName { get; set; } // should be (20) chars only
public string FirstName { get; set; } // should be (10) chars only
...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.