解决方法为用例朋友类在C#

编程入门 行业动态 更新时间:2024-10-25 16:26:02
本文介绍了解决方法为用例朋友类在C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

考虑以下code模式:

Consider the following code pattern:

// Each foo keeps a reference to its manager class Foo { private FooManager m_manager; } // Manager keeps a list of all foos class FooManager { private List<Foo> m_foos; }

问题:没有办法来创建新的Foo和更新两个m_foos列表中FooManager,和m_manager参考在新的Foo实例,而不公开揭露一些下身(和运行有人desyncing列表与实际FOOS的风险) 。

Problem: there is no way to create a new Foo and update both m_foos list in the FooManager, and m_manager reference in the new Foo instance without exposing some privates publicly (and running the risk of someone desyncing the list with actual Foos).

例如。人们可以实现一个构造函数富(FooManager经理)的富。它可以设置m_manager参考,但它没有办法访问m_foos列表。或者,你可以实现在管理CreateFoo()方法。它可以访问m_foos列表中,但是却没有办法在富设置m_manager。

E.g. one could implement a constructor Foo(FooManager manager) in Foo. It could set m_manager reference, but it has no way to access the m_foos list. Or you could implement CreateFoo() method in the manager. It can access m_foos list, but it has no way to set m_manager in Foo.

在C ++中,人们显然会宣布FooManager富来恩preSS的设计意图的朋友,但是这是不可能在C#。我也知道,我可以让富的内部类FooManager来获得,但是这不是一个解决方案,或者(如果美孚可能属于多个经理级?)

In C++, one would obviously declare FooManager a friend of Foo to express the design intent, but this is not possible in C#. I also know that I could make Foo an inner class of FooManager to gain access, but this is not a solution either (what if Foo could belong to more than one manager class?)

顺便说一句。我知道在.NET中的内部的访问,但它要求Foo和FooManager自立门户在一个单独的程序,这是不能接受的。

Btw. I know about "internal" access in .NET, but it requires that Foo and FooManager live on their own in a separate assembly, which is not acceptable.

任何解决方法,如果没有做私人的东西公开?

Any workarounds for that without making private stuff public?

推荐答案

如果我所有的正确理解:

If I understand all correctly:

public abstract class FooBus { protected static FooBus m_bus; } public sealed class Foo : FooBus { private FooManager m_manager; public Foo(FooManager fm) { if (fm == null) { throw new ArgumentNullException("Use FooManager.CreateFoo()"); } if (m_bus != fm) { throw new ArgumentException("Use FooManager.CreateFoo()"); } m_manager = fm; } } public class FooManager : FooBus { private List<Foo> m_foos = new List<Foo>(); public Foo CreateFoo() { m_bus = this; Foo f = new Foo(this); m_foos.Add(f); m_bus = null; return f; } }

更多推荐

解决方法为用例朋友类在C#

本文发布于:2023-11-04 17:41:36,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1558588.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:解决方法   朋友

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!