要访问私有数组,类是双层包装的

问题描述 投票:0回答:1

包含数组变量和类中的类。我知道如何使用一般反射,但是类是重复的,并且中间变量是数组的形式。你能帮我解决这个问题吗?

using System.Reflection;
using space1;
using space2;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;


namespace space1
{
    public class BigClass
    {
        BigClass.SmallClass[] CustomArrays;

        public BigClass()
        {
            this.CustomArrays = new BigClass.SmallClass[2];
            CustomArrays[0] = new SmallClass(17);
            CustomArrays[1] = new SmallClass(18);
        }

        private class SmallClass
        {
            private int MyGoal;
            public SmallClass(int a)
            {
                MyGoal = a;
            }
        }
    }
}

namespace space2
{
    class Program
    {
        public static void Main(string[] args)
        {
            Console.WriteLine("Start");
            BigClass a = new BigClass();

            FieldInfo fieldinfo1 = typeof(BigClass).GetField("CustomArrays", BindingFlags.Instance | BindingFlags.NonPublic);


            Console.WriteLine();
            //Console.WriteLine(fieldinfo2.ToString());
        }
    }
}

我想最终获得 space1 的 MyGoal 值,并通过将该值+1 来返回数字 18。我是否必须先访问 Field,然后再次访问 Field?在接近第一个字段后,我尝试了 GetType()、GetTypeof() 等,但无法访问下一个字段。另外,既然它被声明为数组,我如何判断它是[0]还是[1]? 如果打印出上面写的代码的字段,它只会显示为 CustomArray。我如何通过数组单独使用它?

c# arrays reflection accessibility private
1个回答
0
投票

我猜我上次给你的建议没有帮助,因为你已经重新发布了。这样做仍然是一个“非常糟糕的主意”——如果您需要访问某些数据,请将其公开。如果它不公开,通常有一个很好的理由。 有了这个结构

public class Parent { private Child[] childRefs; public Parent() { childRefs = [new Child(5), new Child(6), new Child(7)]; } private class Child { private int innerValue; public Child(int value) { innerValue = value; } } }

通过两次反射就可以得到
innerValue

的值。无需直接在代码中使用类型

Child
var parent = new Parent();

FieldInfo childRefField = typeof(Parent).GetField("childRefs", BindingFlags.Instance | BindingFlags.NonPublic)!;
IEnumerable childRefFieldValues = (childRefField.GetValue(parent) as IEnumerable)!;

foreach (var childRefFieldValue in childRefFieldValues)
{
    FieldInfo childInternalField = childRefFieldValue.GetType().GetField("innerValue", BindingFlags.Instance | BindingFlags.NonPublic)!;
    int? childInternalValue = childInternalField.GetValue(childRefFieldValue) as int?;
    Console.WriteLine(childInternalValue);
}

这将打印 5、6、7。

© www.soinside.com 2019 - 2024. All rights reserved.