解决方法为用例朋友类在C# [英] Workaround for an use-case of friend classes in 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#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!