为什么在基类不Type.GetFields()的返回后备字段? [英] Why doesn't Type.GetFields() return backing fields in a base class?

查看:747
本文介绍了为什么在基类不Type.GetFields()的返回后备字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C#中,如果使用 Type.GetFields()与一类代表一个派生类中,它会返回一个)在派生类中的所有显式声明的领域,B )在派生类中自动属性以及所有支持领域C)在基类中的所有显式声明的领域。

In C#, if you use Type.GetFields() with a type representing a derived class, it will return a) all explicitly declared fields in the derived class, b) all backing fields of automatic properties in the derived class and c) all explicitly declared fields in the base class.

为什么在自动属性的四)后备字段?基类丢失

Why are the d) backing fields of automatic properties in the base class missing?

例如:

public class Base {
    public int Foo { get; set; }
}
public class Derived : Base {
    public int Bar { get; set; }
}
class Program {
    static void Main(string[] args) {
        FieldInfo[] fieldInfos = typeof(Derived).GetFields(
            BindingFlags.Public | BindingFlags.NonPublic |
            BindingFlags.Instance | BindingFlags.FlattenHierarchy
        );
        foreach(FieldInfo fieldInfo in fieldInfos) {
            Console.WriteLine(fieldInfo.Name);
        }
    }
}

这将只显示后盾酒吧,不富。领域

This will show only the backing field of Bar, not Foo.

推荐答案

一个领域是一个支持字段对反射没有影响。支持字段的唯一相关的特性是它们是私有的。

A field being a backing field has no influence on reflection. The only relevant property of backing fields is that they are private.

反射函数不返回的私人的基类的成员,就算你使用 FlattenHierarchy 。您将需要循环手动在你的类层次结构,并要求对每一个私人领域。

Reflection functions don't return private members of base classes, even if you use FlattenHierarchy. You will need to loop manually over your class hierarchy and ask for private fields on each one.

我觉得 FlattenHierarchy 写入的意图,显示所有成员可见在你看看类代码。因此,基地成员可以隐藏/由成员具有相同名称更派生类中的阴影和私有成员不可见。

I think FlattenHierarchy is written with the intent to show all members visible to code in the class you look at. So base members can be hidden/shadowed by members with the same name in a more derived class and private members are not visible at all.

这篇关于为什么在基类不Type.GetFields()的返回后备字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆