C# 这个反射代码有什么问题?GetFields() 正在返回一个空数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1040803/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 06:46:24  来源:igfitidea点击:

What's wrong with this reflection code? GetFields() is returning an empty array

c#reflectiontype-parameter

提问by Chris McCall

C#, Net 2.0

C#,网络 2.0

Here's the code (I took out all my domain-specific stuff, and it still returns an empty array):

这是代码(我取出了所有特定于域的东西,它仍然返回一个空数组):

using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            ChildClass cc = new ChildClass();
            cc.OtherProperty = 1;

            FieldInfo[] fi = cc.GetType().GetFields();
            Console.WriteLine(fi.Length);
            Console.ReadLine();
        }
    }
    class BaseClass<T>
    {
        private int myVar;

        public int MyProperty
        {
            get { return myVar; }
            set { myVar = value; }
        }


    }

    class ChildClass : BaseClass<ChildClass>
    {
        private int myVar;

        public int OtherProperty
        {
            get { return myVar; }
            set { myVar = value; }
        }

    }
}

采纳答案by Jon Skeet

The parameterless GetFields()returns publicfields. If you want non-public ones, use:

无参数GetFields()返回公共字段。如果您想要非公开的,请使用:

cc.GetType().GetFields(BindingFlags.Instance | BindingFlags.NonPublic);

or whatever appropriate combination you want - but you doneed to specify at least one of Instanceand Static, otherwise it won't find either. You can specify both, and indeed public fields as well, to get everything:

或您想要的任何适当组合 - 但您确实需要指定至少一个Instanceand Static,否则它不会找到。您可以同时指定两个字段,实际上也可以指定公共字段,以获取所有内容:

cc.GetType().GetFields(BindingFlags.Instance | 
                       BindingFlags.Static |
                       BindingFlags.NonPublic |
                       BindingFlags.Public);

回答by Reed Copsey

Since the field is private, you need to use the overload of GetFields() that allows you to specify BindingFlags.NonPublic.

由于该字段是私有的,您需要使用 GetFields() 的重载来指定BindingFlags.NonPublic

To make this work, change it to:

要使其工作,请将其更改为:

FieldInfo[] fi = cc.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance);

回答by AgileJon

You need to specify that you want the private (NonPublic) fields

您需要指定您想要的私有 (NonPublic) 字段

Change to:

改成:

FieldInfo[] fi = cc.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance);