Home > Backend Development > C++ > How Can I Achieve C# Equivalence to C 's 'Friend' Keyword?

How Can I Achieve C# Equivalence to C 's 'Friend' Keyword?

Mary-Kate Olsen
Release: 2024-12-31 21:59:11
Original
329 people have browsed it

How Can I Achieve C# Equivalence to C  's

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")]
Copy after login

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;
}
Copy after login

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);
    }
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template