如何访问嵌套类的私有成员? [英] how to get access to private members of nested class?

查看:141
本文介绍了如何访问嵌套类的私有成员?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

背景:我附上(父)E级嵌套N级与E.在封闭的(父)类我做一些计算,我对嵌套类的每个实例设置值N个多个实例。事情是这样的:

Background: I have enclosed (parent) class E with nested class N with several instances of N in E. In the enclosed (parent) class I am doing some calculations and I am setting the values for each instance of nested class. Something like this:

n1.field1 = ...;
n1.field2 = ...;
n1.field3 = ...;
n2.field1 = ...;
...



这是一个大的eval方法(在父类)。我的目的是 - 因为所有的计算都在父类(他们不能在每个嵌套的实例来完成,因为它会使得代码更复杂) - 使制定者只提供给父类和getter公众。

It is one big eval method (in parent class). My intention is -- since all calculations are in parent class (they cannot be done per nested instance because it would make code more complicated) -- make the setters only available to parent class and getters public.

和现在有一个问题:


  • 当我提出的制定者私人,父类不能存取权限它们

  • 当我让他们公开,每个人都可以更改值

  • 和C#没有朋友的概念

  • 我无法在构造函数中,因为使用懒评价机制(这样的情况下,有引用它们时所创造的 - 我创建的所有对象和计算是按需触发)传递值

  • when I make the setters private, parent class cannot acces them
  • when I make them public, everybody can change the values
  • and C# does not have friend concept
  • I cannot pass values in constructor because lazy evaluation mechanism is used (so the instances have to be created when referencing them -- I create all objects and the calculation is triggered on demand)

我坚持 - 如何做到这一点(限制访问到父类,没有更多,不会少)

I am stuck -- how to do this (limit access up to parent class, no more, no less)?

我怀疑我会首先得到回答个问题 - 但是你为什么不拆每个每个字段的评价 - 所以我举例回答这个问题:你是怎么计算的集合的最小和最大的价值?在一个快速的方法吗?答案是 - 一通。这就是为什么我有一个eval函数它确实计算,并各领域的一次。

推荐答案

如果这是可能的你把父母和孩子在班级另一个程序,你可以为制定者使用内部的。 ,这是这通常是如何处理在野外

If it's possible for you to put the parent and child classes in another assembly, you can make use of internal for the setters. That's generally how this is dealt with in the wild.

修改

EDIT:

托马斯Levesque的的回答给了我一个想法:

class Program
{
    static void Main(string[] args)
    {
        E myE = new E();

        Console.WriteLine("E.N1.Field1 = " + myE.N1.Field1);
        Console.WriteLine("E.N2.Field1 = " + myE.N2.Field1);
    }

    public interface IN
    {
        int Field1 { get; }
    }

    public class E
    {
        private N _n1 = new N();
        private N _n2 = new N();

        public E()
        {
            _n1.Field1 = 42;
            _n2.Field1 = 23;
        }

        public IN N1
        {
            get { return _n1; }
        }

        public IN N2
        {
            get { return _n2; }
        }

        private class N : IN
        {
            private int _field1;

            public int Field1
            {
                get { return _field1; }
                set { _field1 = value; }
            }
        }
    }
}



根据您需要如何公开的子类 N ,这可能是工作。

这篇关于如何访问嵌套类的私有成员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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