C# Equivalent of the "Friend" Keyword
In C , you can use the "friend" keyword to grant access to private members of a class to other classes. However, this feature is not directly supported in C#. Instead, the InternalsVisibleTo attribute provides a partial equivalent for accessing private members across assemblies.
How to Use InternalsVisibleTo
To enable a class in another assembly to access private members, you can add the InternalsVisibleTo attribute to the assembly manifest. For example, in the AssemblyInfo.cs file, you can use the following code:
[assembly: InternalsVisibleTo("OtherAssembly")]
This attribute makes the internals of your assembly visible to the assembly named "OtherAssembly."
Example
Consider the following class:
internal class TestClass { private int privateValue; }
In a separate assembly, you can create a class to access the privateValue:
public class TesterClass { public void DoSomething(TestClass instance) { // Set the value using reflection instance.GetType().GetField("privateValue", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(instance, 10); } }
By using reflection and the InternalsVisibleTo attribute, you can access private members across assemblies for specific scenarios, such as testing.
The above is the detailed content of How Can I Achieve C# Equivalence to C 's 'Friend' Keyword?. For more information, please follow other related articles on the PHP Chinese website!