Understanding the Lack of Friend Access in C#
In C , the "friend" keyword allows classes to grant access to their private members to certain other classes. However, in C#, there is no direct equivalent of this functionality.
Achieving Similar Access with InternalsVisibleTo
The closest C# equivalent to the "friend" keyword is the InternalsVisibleTo attribute. This attribute allows an assembly to specify that another assembly has access to its internal classes and members.
Example Usage of InternalsVisibleTo
To illustrate how to use this attribute, consider the following example:
AssemblyInfo.cs
[assembly: InternalsVisibleTo("OtherAssembly")]
This attribute, when placed in AssemblyInfo.cs, allows the assembly named "OtherAssembly" to access the internal types and members defined in the assembly where AssemblyInfo.cs resides.
Implementation Note
It's important to note that the InternalsVisibleTo attribute only grants access within the same assembly or assembly that has been granted permission. This means that it cannot be used to expose private members to completely external classes or assemblies.
The above is the detailed content of How Can I Achieve Friend-Like Access in C#?. For more information, please follow other related articles on the PHP Chinese website!