Unsignedassemblies, unsignedassemblies
The access modifier internal in C # enables mutual access between types in the same assembly. However, there is sometimes such a requirement that the type of an assembly can be accessed by some external assembly. If it is set to public, it will be accessed by all external assembly; or in a unit test, the test code runs in another assembly, but you need to access the members in the Assembly marked as internal that are being tested. To meet the above requirements, we can use a metaassembly.
Example:
I created a new "friend assembly.exe" folder on drive D and put all the files (.dll).cs;.exe) in it.
1. Create a new class library, friend_unsigned_A.cs
Using System; using System. collections. generic; using System. linq; using System. text; using System. threading. tasks; using System. runtime. compilerServices; // friend_unsigned_A.cs // Compile with // csc/target: library friend_unsigned_A.cs [assembly: InternalsVisibleTo ("friend_unsigned_ B")] // define friend_unsigned_ B as a metaassembly namespace friend_unsigned_A {// Type is internal by default class Class1 {public void Test () {Console. writeLine ("Class1.Test") ;}// Public type with internal member public class Class2 {internal void Test () {Console. writeLine ("Class2.Test ");}}}
2. Open the VS developer command line. csc/target: library friend_unsigned_A.cs
3. Create a console application
Using System; using System. collections. generic; using System. linq; using System. text; using System. threading. tasks; using friend_unsigned_A; // do not forget to add the namespace // friend_unsigned_ B .cs // Compile with: // csc/r: friend_unsigned_A.dll/out: friend_unsigned_ B .exe friend_unsigned_ B .csnamespace friend_unsigned_ B {class Program {static void Main (string [] args) {// Access an internal type. class1 inst1 = new Class1 (); inst1.Test (); Class2 inst2 = new Class2 (); // Access an internal member of a public type. inst2.Test (); System. console. readLine ();}}}
4. Enter the command line
csc /r:friend_unsigned_A.dll /out:friend_unsigned_B.exe friend_unsigned_B.cs
5. Run friend_unsigned_ B .exe directly.