派生类型的 GetFields [英] GetFields of derived type

查看:44
本文介绍了派生类型的 GetFields的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图反映派生类型中的字段,但它返回了基本类型.

I am trying to reflect the fields in a derived type but it's returning the fields of the base type.

public class basetype
{
    string basevar;
}

public class derivedtype : basetype
{
    string derivedvar;
}

在某些函数中:

derivedtype derived = new derivedtype();

FieldInfo[] fields = derived.GetType().GetFields();

这将返回 basevar,但不会返回derivedvar.我尝试了所有不同的绑定,但似乎没有什么区别.

This will return basevar, but not derivedvar. I've tried all the different bindings and it doesn't seem to make a difference.

此外,我在 ASP.NET 中的 App_Code 中执行此操作,其中 basevar 在 App_Code 中定义,而衍生变量是在 App_Controls 中定义的用户控件,其中类型不在范围内.

Also, I'm doing this in ASP.NET within App_Code where basevar is defined in App_Code and derivedvar is a user control defined in App_Controls where the types are not in scope.

推荐答案

照原样,这不会返回任何内容,因为默认绑定仅适用于公共字段.

As is, this will return nothing as the default binding is for public fields only.

同样,派生类型不是从基类型派生的

As is also, derivedtype isn't derived from basetype

与:

FieldInfo[] fields = derived.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance);

它返回衍生变量.我刚刚检查了 LINQPad.

It returns derivedvar. I've just checked in LINQPad.

如果我将派生类型更改为从基类型派生,那么我可以通过以下方式获取两个字段:

If I change derivedtype to be derived from basetype, then I can get both fields with:

FieldInfo[] fields = derived.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance).Concat(derived.GetType().BaseType.GetFields(BindingFlags.NonPublic | BindingFlags.Instance)).ToArray();

这篇关于派生类型的 GetFields的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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