2017-01-22 117 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; 
}