[英]How to get properties of a class in an array
我有一個學生班,結構如下:
public sealed class Student
{
public string Name {get;set;}
public string RollNo {get;set;}
public string standard {get;set;}
public bool IsScholarshipped {get;set;}
public List<string> MobNumber {get;set;}
}
如何在類似數組中獲取Student類的這些屬性
arr[0]=Name;
arr[1]=RollNo;
.
.
.
arr[4]=MobNumber
並且這些屬性的類型在單獨的數組中
arr2[0]=string;
arr2[1]=string;
.
.
.
arr2[4]=List<string> or IEnumerable
請用大塊代碼解釋一下。
var type = model.GetType();
var properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
那會給你一個PropertyInfo
數組。 然后,您可以執行此操作以獲取名稱:
properties.Select(x => x.Name).ToArray();
你可以使用反射:
foreach (PropertyInfo prop in typeof(Student).GetProperties(BindingFlags.Public | BindingFlags.Instance))
{
'''
}
您可以在GetProperty
的結果上使用LINQ,如下所示:
var props = typeof(Student).GetProperties();
var names = props
.Select(p => p.Name)
.ToArray();
var types = props
.Select(p => p.PropertyType)
.ToArray();
for (int i = 0 ; i != names.Length ; i++) {
Console.WriteLine("{0} {1}", names[i], types[i]);
}
這是打印的內容:
Name System.String
RollNo System.String
standard System.String
IsScholarshipped System.Boolean
MobNumber System.Collections.Generic.List`1[System.String]
為此,可以使用operator []重載。 可以使用PropertyInfo映射屬性。
public sealed class Student
{
public string Name { get; set; }
public string RollNo { get; set; }
public string Standard { get; set; }
public bool IsScholarshipped { get; set; }
public List<string> MobNumber { get; set; }
public object this[int index]
{
get
{
// Note: This may cause IndexOutOfRangeException!
var propertyInfo = this.GetType().GetProperties()[index];
return propertyInfo != null ? propertyInfo.GetValue(this, null) : null;
}
}
public object this[string key]
{
get
{
var propertyInfo = this.GetType().GetProperties().First(x => x.Name == key);
return propertyInfo != null ? propertyInfo.GetValue(this, null) : null;
}
}
}
然后你可以這樣使用這個類:
var student = new Student { Name = "Doe, John", RollNo = "1", IsScholarshipped = false, MobNumber = new List<string>(new[] { "07011223344" }) };
var nameByIndex = student[0] as string;
var nameByKey = student["Name"] as string;
閱讀msdn上有關[]運算符的更多信息。
請注意,以這種方式按索引訪問屬性很容易出錯,因為屬性的順序很容易在沒有任何控制的情況下改變。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.