On MSDN, explain internal as follows:
The internal keyword is a access modifier for types and type. Internal types or members is accessible only within files in the same assembly.
That is, only code in the same assembly is allowed to call a type or member.
So is it possible to invoke these internal methods?
If the assembly is called, and InternalsVisibleToAttribute is used in the code to mark one or more friend assemblies, then those assemblies that are labeled friends can access the internal method of the called Assembly. The following example is the code for assembly A, which declares AssemblyB as a friend assembly
This file was for Assembly a.using system.runtime.compilerservices;using System; [Assembly:internalsvisibleto ("AssemblyB")]//the class is internal by default.class friendclass{public void Test () { Console.WriteLine ("Sample Class");} } Public class This has an internal method.public class classwithfriendmethod{ internal void Test () { Consol E.writeline ("Sample Method");} }
A more specific line of code example is as follows:
[Assembly:internalsvisibleto ("AssemblyB, PUBLICKEY=32AB4BA45E0A69A1")]
So what if we're going to call the internal method in the code written by a third party?
The answer is to use reflection.
The following is the source code for the called Class.
Using system;using system.collections.generic;using system.linq;using system.text;namespace internalclasstest{ public class Pubclass {public void Speak () { Console.WriteLine ("Pubclass speaks:you is so nice!"); } Internal method Internal void Mock () { Console.WriteLine ("Pubclass mocks:you suck!"); } } Internal class class Internalclass {public void Speak () { Console.WriteLine (" Internalclass speaks:i Love My job! "); } void Moci () { Console.WriteLine ("Internalclass speaks:i Love Friday night!"); } }
Here is a code example that uses reflection and calls Pubclass's internal function mock:
Using system;using system.collections.generic;using system.linq;using system.text;using System.Reflection;namespace reflectioninternal{ class program { static void Main (string[] args) { Assembly asm = Assembly.loadfile (@ "E:\internalclasstest\bin\Debug\internalclasstest.dll"); Type T1 = asm. GetType ("Internalclasstest. Pubclass "); ConstructorInfo t1constructor = t1. GetConstructor (type.emptytypes); Object Opubclass = T1constructor.invoke (new object[] {}); MethodInfo Omethod = t1. GetMethod ("Mock", BindingFlags.Instance | BindingFlags.NonPublic); Omethod.invoke (Opubclass, New object[]{});}}
Methods for calling internal using reflection in C #