Accessing internal classes in other assemblies
RyzenAdorer 2021-06-04 10:26:55

Preface

This article describes how to access... In other assemblies internal Class method
First, let's create a new solution , Two new class libraries are created at the same time FooALibray and FooALibray, as follows :

among FooA The class code is as follows :

 internal class FooA
{
public void Print()
{
Console.WriteLine($"I am {nameof(FooA)}");
}
}

And then we were in Program Class call FooA Of Print Method :

 static void Main(string[] args)
{
var fooA = new FooALibrary.FooA();// Report errors ,FooA inaccessible , Because it has a certain level of protection
fooA.Print();
}

So how can we access it internal Grade FooA Class? ?

InternalsVisibleToAttribute characteristic

First , We are in the project FooALibray newly added -> Assembly information file , So get an initial AssemblyInfo The class , Then we just need to add the following code :

[assembly: InternalsVisibleTo("InternalsVisibleToAttributeSample")]

that , If the previous code can be compiled normally, the output will be :

I am FooA

Expansion part

hypothesis FooBLibray Also visit FooA, Do you want to add another pair of FooBLibray What about assemblies ? The answer is No , You can also use the following :

take FooBLibray Change the assembly name to InternalsVisibleToAttributeSample

 public class FooB
{
public void PrintA()
{
new FooALibrary.FooA().Print();// Compile successfully
}
}

This black technology is what elder brother Lin told me , Hey ~~

summary

We make good use of InternalsVisibleToAttribute Assembly visibility can be used. We need to write Demo Or unit tests should be referred to internal Don't pollute when you are in class ( Modified into public) You can access it , This feature is very useful in daily workflow

Please bring the original link to reprint ,thank
Similar articles

2021-08-09

2021-08-09