如何从父类获取属性

时间:2019-02-26 18:25:35

标签: c# .net getproperties

我想使用GetProperties通过孩子从父类中获取属性,尽管进行了研究,但还是失败了。

我尝试了下一个,但没有任何结果:

PropertyInfo[] fields = t.GetProperties();
PropertyInfo[] fields1 = t.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.FlattenHierarchy);
PropertyInfo[] propNames = t.BaseType.GetProperties( BindingFlags.Public | BindingFlags.Instance);

仅从子类获得属性,但不从父类获得属性。

课程

public class A: B
{
    public string a1 { get; set; }

    public string a2 { get; set; }

    public string a3 { get; set; }

    public string a4 { get; set; }
}

public class B
{
    public string b1;
}

使用此代码,我得到的是A的属性,而不是B中的属性。

此代码有效吗?我需要在某个地方进行配置吗?

1 个答案:

答案 0 :(得分:2)

在您的声明中

public class B
{
    public string b1;
}

b1field,不是属性。您应该

  • 使用GetFields()

    FieldInfo[] fields = t.GetFields();
    

    这将获得字段(按预期方式)-请注意,the documentation表示

      

    通常,只应将字段用于具有私有或受保护的可访问性的变量。

  • b1设置属性,例如通过向其中添加{ get; set; }访问者。