c++的friend关键字允许类a将类B指定为它的friend。这允许类B访问类A的私有/受保护成员。

我从来没有读过任何关于为什么c#(和VB.NET)中不包含这个的东西。大多数关于StackOverflow问题的答案似乎都在说它是c++的一个有用的部分,并且有很好的理由使用它。以我的经验,我不得不同意。

对我来说,另一个问题似乎是在问如何在c#应用程序中做类似于friend的事情。虽然答案通常围绕嵌套类,但它似乎没有使用friend关键字那么优雅。

最初的《设计模式》一书在其示例中经常使用它。

总之,为什么在c#中没有friend,在c#中模拟friend的“最佳实践”方法是什么?

(顺便说一下,internal关键字不是一回事,它允许整个程序集中的所有类访问内部成员,而friend允许你给某个类完全访问另一个类)


当前回答

如果有朋友,c++设计人员可以精确控制私有*成员暴露给谁。但是,他被迫暴露了每一个私人成员。

对于内部,c#设计器可以精确控制他所公开的私有成员集。显然,他只能暴露单个私有成员。但是,它将暴露给程序集中的所有类。

通常,设计人员只希望将少数私有方法暴露给选定的少数其他类。例如,在类工厂模式中,可能希望类C1只由类工厂CF1实例化。因此类C1可能有一个受保护的构造函数和一个友类工厂CF1。

As you can see, we have 2 dimensions along which encapsulation can be breached. friend breaches it along one dimension, internal does it along the other. Which one is a worse breach in the encapsulation concept? Hard to say. But it would be nice to have both friend and internal available. Furthermore, a good addition to these two would be the 3rd type of keyword, which would be used on member-by-member basis (like internal) and specifies the target class (like friend). * For brevity I will use "private" instead of "private and/or protected". - Nick

其他回答

我以前经常使用friend,我不认为它违反了OOP,也不认为它有任何设计缺陷。在一些地方,它是用最少的代码达到正确目的的最有效的方法。

One concrete example is when creating interface assemblies that provide a communications interface to some other software. Generally there are a few heavyweight classes that handle the complexity of the protocol and peer peculiarities, and provide a relatively simple connect/read/write/forward/disconnect model involving passing messages and notifications between the client app and the assembly. Those messages / notifications need to be wrapped in classes. The attributes generally need to be manipulated by the protocol software as it is their creator, but a lot of stuff has to remain read-only to the outside world.

声明协议/“创建者”类对所有创建的类的亲密访问是违反OOP的,这是非常愚蠢的——创建者类不得不在上升的过程中对每一点数据进行修改。我发现最重要的是尽量减少“为了面向对象而面向对象”模型通常导致的所有多余的代码行。额外的意大利面只会产生更多的虫子。

人们知道您可以在属性、属性和方法级别应用内部关键字吗?它不仅仅用于顶级类声明(尽管大多数示例似乎都显示了这一点)。

如果你有一个使用friend关键字的c++类,并且想在一个c#类中模拟它: 1. 将c#类声明为public 2. 将c++中受保护的所有属性/属性/方法声明为c#内部的 3.为所有内部属性和属性的公共访问创建只读属性

我同意它并不完全等同于好友,单元测试是一个非常有价值的例子,说明了需要好友之类的东西(就像协议分析器日志代码一样)。然而,internal提供了您想要公开的类的公开,[InternalVisibleTo()]处理其余的—似乎它是专门为单元测试而生的。

至于朋友“更好,因为你可以显式地控制哪些类可以访问”——一堆可疑的邪恶类在同一个程序集中做什么呢?对程序集进行分区!

这实际上不是c#的问题。这是IL中的一个基本限制。c#也受此限制,就像任何其他寻求可验证的。net语言一样。这个限制也包括c++ /CLI中定义的托管类(Spec第20.5节)。

话虽如此,我认为纳尔逊对为什么这是一件坏事有一个很好的解释。

拥有编程领域的朋友或多或少被认为是“肮脏的”,容易被滥用。它破坏了类之间的关系,破坏了OO语言的一些基本属性。

也就是说,这是一个很好的特性,我自己在c++中使用过很多次;并且也想在c#中使用它。但我敢打赌,因为c#的“纯”OOness(与c++的伪OOness相比),MS决定因为Java没有朋友,关键字c#也不应该(开玩笑;))

严肃地说:内部关系不如朋友关系好,但它确实能完成工作。请记住,您很少会不通过DLL将代码分发给第三方开发人员;因此,只要您和您的团队了解内部类及其使用,就应该没问题。

让我来澄清一下friend关键字是如何破坏OOP的。

私有和受保护的变量和方法可能是OOP中最重要的部分之一。对象可以保存只有它们可以使用的数据或逻辑的思想允许您编写独立于环境的功能实现—并且您的环境不能更改它不适合处理的状态信息。通过使用friend,你将两个类的实现耦合在一起——这比仅仅耦合它们的接口要糟糕得多。

顺便说一句。 使用friend并不是违反封装,相反,它是加强封装。就像访问器+突变器、操作符重载、公共继承、向下强制转换等一样,它经常被误用,但这并不意味着关键字没有,或者更糟,没有一个坏的目的。

请参阅Konrad Rudolph在另一个线程中的消息,或者如果您愿意,请参阅c++常见问题解答中的相关条目。

这种友谊也可以通过使用“代理”——一些内部类来模拟。考虑下面的例子:

public class A // Class that contains private members
{
  private class Accessor : B.BAgent // Implement accessor part of agent.
  {
    private A instance; // A instance for access to non-static members.
    static Accessor() 
    { // Init static accessors.
      B.BAgent.ABuilder = Builder;
      B.BAgent.PrivateStaticAccessor = StaticAccessor;
    }
    // Init non-static accessors.
    internal override void PrivateMethodAccessor() { instance.SomePrivateMethod(); }
    // Agent constructor for non-static members.
    internal Accessor(A instance) { this.instance = instance; }
    private static A Builder() { return new A(); }
    private static void StaticAccessor() { A.PrivateStatic(); }
  }
  public A(B friend) { B.Friendship(new A.Accessor(this)); }
  private A() { } // Private constructor that should be accessed only from B.
  private void SomePrivateMethod() { } // Private method that should be accessible from B.
  private static void PrivateStatic() { } // ... and static private method.
}
public class B
{
  // Agent for accessing A.
  internal abstract class BAgent
  {
    internal static Func<A> ABuilder; // Static members should be accessed only by delegates.
    internal static Action PrivateStaticAccessor;
    internal abstract void PrivateMethodAccessor(); // Non-static members may be accessed by delegates or by overrideable members.
  }
  internal static void Friendship(BAgent agent)
  {
    var a = BAgent.ABuilder(); // Access private constructor.
    BAgent.PrivateStaticAccessor(); // Access private static method.
    agent.PrivateMethodAccessor(); // Access private non-static member.
  }
}

如果只用于访问静态成员,则会简单得多。 这种实现的好处是,所有类型都在友谊类的内部作用域中声明,并且与接口不同,它允许访问静态成员。