[英]Using Reflection to Get Class Property Information returning nothing
我的任務是更新大量具有相同數據類型的記錄,並希望以這樣的方式編寫它,我不必找到每個 class object 並手動執行它們。 因此,我認為最好的方法是使用PropertyInfo
進行反射。
在問這個問題之前,我已經看過以下內容;
獲取 object 的所有屬性如何獲取 class 的屬性列表? https://www.codegrepper.com/code-examples/csharp/c%23+get+all+class+properties https://docs.microsoft.com/en-us/dotnet/api/system.type.getproperties ?view=net-5.0
看着這個,建議我采用正確的方法,但對於我的生活,我沒有得到結果。
代碼如下
void Main()
{
var propeties = typeof(MaterialsStructure).GetProperties(BindingFlags.Public | BindingFlags.Static);
}
public class MaterialsStructure
{
public ExistingProposedDescriptionStructure boundariesField;
public ExistingProposedDescriptionStructure ceilingsField;
}
public class ExistingProposedDescriptionStructure
{
public string Existing { get; set; }
public string Proposed { get; set; }
public bool NotApplicable { get; set; }
public bool DontKnow { get; set; }
}
問題是,當我檢查屬性時,它在數組中有 0 個項目,我原以為它有兩個ExistingProposedDescriptionStructure
類型的屬性。 如果有人能告訴我我在哪里出錯了,我將不勝感激。
您的MaterialsStructure
class 沒有屬性,它有字段。 有關詳細信息,請參見此處。 所以要么這樣做:
var fields = typeof(MaterialsStructure).GetFields();
或更改您的 class:
public class MaterialsStructure
{
public ExistingProposedDescriptionStructure boundariesField { get; set;}
public ExistingProposedDescriptionStructure ceilingsField { get; set;}
}
現在這將起作用:
var propeties = typeof(MaterialsStructure).GetProperties();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.