简体   繁体   English

如何在C#和VB.NET中模拟C ++朋友?

[英]How to simulate C++ friend in C# and VB.NET?

Because sometimes, I really need a friend. 因为有时候,我真的需要一个朋友。

I can think of the following tricks: 我可以想到以下技巧:

  1. Read only wrapper - like ReadOnlyCollection . 只读包装器 - 如ReadOnlyCollection The friend keeps the pointer to the modifiable object, while everyone else can access only the wrapper. 朋友保持指向可修改对象的指针,而其他人只能访问包装器。
  2. Write delegate - the friend gives the constructor of the object a reference to a delegate as one of the parameters, the constructor fills it with an address to a private method that can be used to modify the object. 写委托 - 朋友给对象的构造函数一个对委托的引用作为参数之一,构造函数用一个地址填充它,可以用来修改对象的私有方法。
  3. Reflection - obviously a bad idea. 反思 - 显然是一个坏主意。 Included for completeness. 包括完整性。
  4. Multiple assemblies - put your friends together in a separate assembly and set your modifier methods internal . 多个程序集 - 将您的朋友放在一个单独的程序集中,并将修改器方法设置为internal
  5. Expose the modifiable object, but add comments to modifier methods "This is an infrastructure method - don't call it!" 公开可修改的对象,但是为修改器方法添加注释“这是一种基础结构方法 - 不要调用它!”
  6. Nested classes. 嵌套类。
  7. Add System.ComponentModel.EditorBrowsable(System.ComponentModel. EditorBrowsableState.Never) attribute to the member you want only the friend to access to hide it from IntelliSense. System.ComponentModel.EditorBrowsable(System.ComponentModel. EditorBrowsableState.Never)属性添加到您只希望朋友访问的成员,以将其从IntelliSense中隐藏。
  8. Implicit interface implementation - see comments. 隐式接口实现 - 请参阅注释。

Is this list exhaustive? 这份清单详尽无遗吗? Can anyone sort these in order of decreasing performance? 任何人都可以按性能降低的顺序排序吗? Order of decreasing neatness? 降低整洁度的顺序? Any suggestions when to use which? 有什么建议什么时候使用哪个?

You can also use the InternalsVisibleTo attribute. 您还可以使用InternalsVisibleTo属性。

For a given assembly, A, you can specify which other assemblies can have access to A's internal types. 对于给定的程序集A,您可以指定哪些其他程序集可以访问A的内部类型。

In c# Nested classes (like private classes) are similar to friend in c++: 在c#中,嵌套类(如私有类)与c ++中的friend类似:

public class Root
{
   private int a; // accessible for friendroot

   public int b;

   public class FriendOfRoot
   {          
      public int d;
   }

}

Edit: If the simulation of friend with nested classes provided here is useful for you, in performance it's fast enough like regular classes (In compile all things will be determined and there is no casting issues and no overhead). 编辑:如果这里提供的嵌套类的朋友的模拟对你有用,那么在性能上它就像常规类一样快(在编译时所有事情都将被确定,并且没有投射问题且没有开销)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM