2017-01-22 108 views
1

我正在爲我的第一個項目開發商業模式(請原諒,如果有人發現我的代碼缺乏質量,重要的是我正在取得進展)。我被困在試圖找出錯誤的原因。我正在創建一個依賴於屬性和自定義屬性反映的視圖。當我在Property屬性中第二次使用PropertyInfo.GetCustomAttribute時,我得到一個空引用異常。爲什麼我的第二個調用返回null。正如你所看到的,我已經在屬性上調用了屬性(_TopSchools),我調用了該方法。獲取PropertyInfo.GetCustomAttribute的例外<T>

public class EducationFilter : Filter 
{ 
    [FilterAttribute(FilterType.Child, "Topschools")]//I cant get this attr! 
    public TopSchoolFilter _TopSchool { get; set; } 
} 

public class TopSchoolFilter :BooleanFilter 
{ 

} 

public class Filters 
{ 
    [FilterAttribute(FilterType.Parent, "Education")] //This i can... 
    public EducationFilter _EducationFilter { get; set; } 

    public Filters(EducationFilter educationFilter) 
    { 
     this._EducationFilter = educationFilter; 
    } 
} 

public StackLayout GenerateFilterView(PropertyInfo p,TestModel vm) 
     { 
      StackLayout tempStack = new StackLayout(); 
      **FilterAttribute filterAttr = p.GetCustomAttribute<FilterAttribute>();**//This returns the attr instance 
      IEnumerable<PropertyInfo> filterProperties = p.PropertyType.GetRuntimeProperties(); 

      foreach (PropertyInfo p1 in filterProperties) 
      { 
       **FilterAttribute filterAttr1 = p1.GetCustomAttribute<FilterAttribute>();**//But not this one, i get null 
+0

如果您得到空值,那就意味着有問題的屬性沒有您要求的屬性。檢查'p1.Name'並確保它是你期待的屬性,否則只是跳過沒有屬性的屬性? – cdhowie

+1

cdhowie,幫助我追蹤問題。我有一些從基類繼承的屬性,劑量有屬性。謝謝! – arif

+0

你在傳遞什麼「p」?(PropertyInfo p,TestModel vm) –

回答

0

如果GetCustomAttribute<T>()返回null那麼這意味着自定義屬性提供商(在這種情況下,屬性)不具有該類型的屬性。如果您只對具有此屬性的屬性感興趣,則可以跳過沒有屬性的屬性。

if (filterAttr1 == null) { 
    continue; 
}