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

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

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

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

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

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


当前回答

您可以保持它为私有,并使用反射来调用函数。测试框架可以做到这一点,如果你要求它测试一个私有函数

其他回答

我读过许多关于“朋友”关键字的聪明评论,我同意它是有用的东西,但我认为“内部”关键字没有那么有用,而且它们对纯OO编程来说都很糟糕。

我们有什么?(说到“朋友”,我也说到“内部”)

使用“friend”是否会使代码对于oo不那么纯粹? 是的, 不使用“friend”会使代码更好吗? 不,我们仍然需要在类之间建立一些私人关系,而且只有打破了我们美丽的封装才能做到,所以这也不好,我可以说它比使用“朋友”更邪恶。

使用friend会产生一些局部问题,不使用friend会给代码库用户带来问题。

在我看来,编程语言的通用解决方案是这样的:

// c++ style
class Foo {
  public_for Bar:
    void addBar(Bar *bar) { }
  public:
  private:
  protected:
};

// c#
class Foo {
    public_for Bar void addBar(Bar bar) { }
}

你觉得怎么样?我认为这是最常见的纯面向对象的解决方案。你可以对你想要的任何类打开任何方法的访问。

我以前经常使用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()]处理其余的—似乎它是专门为单元测试而生的。

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

我只回答“如何”的问题。

这里有很多答案,但我想提出一种“设计模式”来实现这一功能。我将使用简单的语言机制,包括:

接口 嵌套类

例如,我们有两个主要的类:学生和大学。学生的GPA只有大学才允许获得。代码如下:

public interface IStudentFriend
{
    Student Stu { get; set; }
    double GetGPS();
}

public class Student
{
    // this is private member that I expose to friend only
    double GPS { get; set; }
    public string Name { get; set; }

    PrivateData privateData;

    public Student(string name, double gps) => (GPS, Name, privateData) = (gps, name, new PrivateData(this);

    // No one can instantiate this class, but Student
    // Calling it is possible via the IStudentFriend interface
    class PrivateData : IStudentFriend
    {
        public Student Stu { get; set; }

        public PrivateData(Student stu) => Stu = stu;
        public double GetGPS() => Stu.GPS;
    }

    // This is how I "mark" who is Students "friend"
    public void RegisterFriend(University friend) => friend.Register(privateData);
}

public class University
{
    var studentsFriends = new List<IStudentFriend>();

    public void Register(IStudentFriend friendMethod) => studentsFriends.Add(friendMethod);

    public void PrintAllStudentsGPS()
    {
        foreach (var stu in studentsFriends)
            Console.WriteLine($"{stu.Stu.Name}: stu.GetGPS()");
    }
}

public static void Main(string[] args)
{
    var Technion = new University();
    var Alex     = new Student("Alex", 98);
    var Jo       = new Student("Jo", 91);

    Alex.RegisterFriend(Technion);
    Jo.RegisterFriend(Technion);
    Technion.PrintAllStudentsGPS();

    Console.ReadLine();
}

如果你正在使用c++,你发现你自己使用friend关键字,这是一个非常强烈的迹象,你有一个设计问题,因为为什么一个类需要访问其他类的私有成员?

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

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.
  }
}

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