有什么不对的反射代码? GetFields()将返回一个空数组 [英] What's wrong with this reflection code? GetFields() is returning an empty array

查看:1519
本文介绍了有什么不对的反射代码? GetFields()将返回一个空数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C#.NET 2.0



下面的代码(我拿出我所有的特定领域的东西,它仍然会返回一个空数组):

 使用系统; 
使用System.Collections.Generic;
使用System.Text;
使用的System.Reflection;

命名ConsoleApplication1
{
类节目
{
静态无效的主要(字串[] args)
{
ChildClass CC =新ChildClass();
cc.OtherProperty = 1;

的FieldInfo [] F1 = cc.GetType()GetFields();
Console.WriteLine(fi.Length);
到Console.ReadLine();
}
}
类BaseClass的< T>
{
私人诠释myVar的;

公众诠释myProperty的
{
得到{myVar的; }
集合{myVar的=价值; }
}


}

类ChildClass:BaseClass的< ChildClass>
{
私人诠释myVar的;

公众诠释OtherProperty
{
得到{myVar的; }
集合{myVar的=价值; }
}

}
}


解决方案

无参数 GetFields()返回公共的领域。如果您希望非公开的人,请使用:

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

或任何适当组合你想要的 - 但你的的需要指定至少实例静态之一,否则将找不到任何。您可以同时指定这两个,确实公共领域,把一切:

  cc.GetType()GetFields(的BindingFlags。实例| 
BindingFlags.Static |
BindingFlags.NonPublic可|
BindingFlags.Public);


C#, Net 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; }
        }

    }
}

解决方案

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

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

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

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

这篇关于有什么不对的反射代码? GetFields()将返回一个空数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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