Why does C# not provide the C++ style 'friend' keyword?
The C++ friend keyword allows a class A
to designate class B
as its friend. This allows Class B
to access the private
/ protected
members of class A
.
I've never read anything as to why this was left out of C# (and VB.NET). Most answers to this earlier StackOverflow question seem to be saying it is a useful part of C++ and there are good reasons to use it. In my experience I'd have to agree.
Another question seems to me to be really asking how to do something similar to friend
in a C# application. While the answers generally revolve around nested classes, it doesn't seem quite as elegant as using the friend
keyword.
The original Design Patterns book uses it regularly throughout its examples.
So in summary, why is friend
missing from C#, and what is the "best practice" way (or ways) of simulating it in C#?
(By the way, the internal
keyword is not the same thing, it allows all classes within the entire assembly to access internal
members, while friend
allows you to give a certain class complete access to exactly one other class)
Having friends in programming is more-or-less considered "dirty" and easy to abuse. It breaks the relationships between classes and undermines some fundamental attributes of an OO language.
That being said, it is a nice feature and I've used it plenty of times myself in C++; and would like to use it in C# too. But I bet because of C#'s "pure" OOness (compared to C++'s pseudo OOness) MS decided that because Java has no friend keyword C# shouldn't either (just kidding ;))
On a serious note: internal is not as good as friend but it does get the job done. Remember that it is rare that you will be distributing your code to 3rd party developers not though a DLL; so as long as you and your team know about the internal classes and their use you should be fine.
EDIT Let me clarify how the friend keyword undermines OOP.
Private and protected variables and methods are perhaps one of the most important part of OOP. The idea that objects can hold data or logic that only they can use allows you to write your implementation of functionality independent of your environment - and that your environment cannot alter state information that it is not suited to handle. By using friend you are coupling two classes' implementations together - which is much worse then if you just coupled their interface.
On a side note. Using friend is not about violating the encapsulation, but on the contrary it's about enforcing it. Like accessors+mutators, operators overloading, public inheritance, downcasting, etc., it's often misused, but it does not mean the keyword has no, or worse, a bad purpose.
See Konrad Rudolph's message in the other thread, or if you prefer see the relevant entry in the C++ FAQ.
有关信息,.NET中的另一个相关但并非完全相同的东西是[InternalsVisibleTo]
,它允许组件指定另一个组件(例如单元测试组件)(有效地)对类型具有“内部”访问/原始程序集中的成员。
上一篇: 单身人士真的很糟糕吗?