简体   繁体   English

在PropertyInfo.GetCustomAttribute上获得一个例外<T>

[英]Get an exception on PropertyInfo.GetCustomAttribute<T>

I'm working on the business model for my first project(please excuse me if someone finds my code lack of quality, important thing is i'm making progress). 我正在研究我的第一个项目的商业模式(如果有人发现我的代码缺乏质量,请原谅我,重要的是我正在取得进展)。 I'm stuck trying to find the reason for a bug. 我一直在试图找出错误的原因。 I'm creating a view which rely on reflection of properties and custom attributes. 我正在创建一个依赖于属性和自定义属性反射的视图。 I get a null reference exception when i use the PropertyInfo.GetCustomAttribute for the second time on a "property's property". 当我在“属性的属性”上第二次使用PropertyInfo.GetCustomAttribute时,我得到一个空引用异常。 Why does my second call return null. 为什么我的第二个调用返回null。 As you can see I have applied the attribute on the property(_TopSchools) which i invoke method on. 正如您所看到的,我已在我调用方法的属性(_TopSchools)上应用了该属性。

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

If GetCustomAttribute<T>() returns null then that means the custom attribute provider (the property in this case) doesn't have an attribute of that type. 如果GetCustomAttribute<T>()返回null则表示自定义属性提供程序(在本例中为属性)不具有该类型的属性。 If you are only interested in properties with this attribute, you can just skip over the properties without the attribute. 如果您只对具有此属性的属性感兴趣,则可以跳过没有该属性的属性。

if (filterAttr1 == null) {
    continue;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM