簡體   English   中英

如何將當前實例傳遞給實例內部的FieldInfo.GetValue?

[英]How to pass the current instance to FieldInfo.GetValue inside the instance?

我正在制作一個抽象類,需要驗證其后代中的字段。 所有已驗證的字段均由一個屬性標記,並假定檢查是否為空或為空。 為此,我獲得了該類中的所有字段:

var fields = this.GetType().GetFields().Where(field => Attribute.IsDefined(field, typeof(MyAttribute))).ToList(); 

然后,對於每個FieldInfo,我都嘗試這樣做:

if (string.IsNullOrEmpty(field.GetValue(this).ToString()))
{
    // write down the name of the field
}

我得到一個System.NullReferenceException:對象引用未設置為object的實例

我知道我想將一個類的實例傳遞給GetValue方法。 但是,如何傳遞當前實例(啟動邏輯的實例)?

或:還有其他獲取領域價值的方法嗎?

GetValue調用很好。 問題出在調用ToString的返回值上。

如果GetValue返回null ,則將在此null值上調用ToString ,這將引發NullReferenceException

做這樣的事情:

var value = field.GetValue(this);
if (value == null || string.IsNullOrEmpty(value.ToString()))
{
    // write down the name of the field
}

正如盧卡斯所說,問題是您不應該調用ToString()時。 大概您的屬性無論如何都應該僅應用於字符串字段,因此最簡單的方法就是將結果轉換為string 如果該強制轉換失敗,則表明存在較大的錯誤(屬性應用不正確)。

if (string.IsNullOrEmpty((string) field.GetValue(this)))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM