【问题标题】:How to get properties from parent class如何从父类获取属性
【发布时间】:2019-02-26 18:25:35
【问题描述】:

我想使用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 中的属性。

此代码有效吗?我需要在某个地方配置一些东西吗?

【问题讨论】:

  • 您能否给我们一个示例,看看您的示例类是什么样的,即child 及其parent 类?
  • 这段代码按预期工作,我得到了所有基本类型属性。那么你想达到什么目的呢?
  • @Dandré 做到了。感谢您的支持。
  • @亚历山大。只是试图获取在父类上设置的属性(在本例中为属性)--> B.

标签: c# .net getproperties


【解决方案1】:

在你的声明中

public class B
{
    public string b1;
}

b1field,而不是属性。你应该

  • 使用GetFields():

    FieldInfo[] fields = t.GetFields();
    

    这将获得字段(如预期的那样) - 请注意 the documentation 表示

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

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

【讨论】:

    猜你喜欢
    • 2015-02-02
    • 1970-01-01
    • 1970-01-01
    • 2019-11-14
    • 1970-01-01
    • 1970-01-01
    • 2019-08-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多