The internal keyword in C# can make the marked methods, fields or attributes only available within the current assembly, so what if other assemblies need to use this internal method? .NET provides a way to accomplish this function similar to the friend class in C++, which is to use InternalsVisibleTo.
This is common when doing tests, and another project is needed to test the functionality marked by the internal method in the project, so with InternalsVisibleTo, we don't have to change a method that should not be public to public in order to do unit testing.
There are still some things to pay attention to when using InternalsVisibleTo, especially PublicKey is not easy to understand, let's talk about how to use this InternalsVisibleTo:
Let's first explain the premise: Project1 is a functional project, and Project1.Test (assembly name: Project1.Test.dll) is a test project for Project1.
1. Open the Assembly.cs file of Project1 and add this sentence to the end of the file:
PublicKey=****** should be replaced with the Project1.Test.dll public key, as for how to get the PublicKey, please see the Notes section at the end of the article.
2. Verify that namespace: System.Runtime.CompilerServices is added to the namespace reference of the Assembly.cs, as InternalsVisibleTo is located in the namespace System.Runtime.CompilerService.
Notes:
1. How do I get a PublicKey?
A: Under the command line, use sn -tp Project1.Test.dll to see PublicKey and PublicKeyToken
2. If Project1 is a strong-named project, then InternalsVisibleTo must specify a PublicKey, so Project1.Test must also use a strong signature to use InternalsVisibleTo correctly, otherwise the compilation will make an error, if Project1 does not use a strong signature, Then Project1.Test does not need to use strong signatures, and when using InternalsVisibleTo, only the name of the assembly is required, and there is no need to set the PuklicKey. |