In certain scenarios, you may encounter a situation where an assembly you are using provides a method that returns an object type, but that object actually belongs to an internal class within the inaccessible assembly. This raises the question of how to access the fields and methods of that internal class from your own assembly.
While modifying the vendor-supplied assembly is out of the question, there is a solution if you wish to allow specific assemblies access to the internal members of the vendor assembly for testing purposes. This can be achieved using the InternalsVisibleTo attribute.
In the AssemblyInfo.cs file of your project, add the following line:
[assembly: InternalsVisibleTo("name of assembly here")]
This line grants the specified assembly access to the internal members of your assembly, including the internal class you are trying to access.
Once you have added the InternalsVisibleTo attribute and rebuilt your assembly, you can access the internal class from your external assembly as follows:
public class MyClass { public void AccessTest() { Vendor vendor = new Vendor(); object value = vendor.Tag; // Cast the object to the internal class type InternalClass internalClass = (InternalClass)value; // Access the internal member string test = internalClass.test; } }
Note: It's important to ensure that the assembly you grant access to is used for testing purposes only, as it can compromise the security of your application if used in production.
The above is the detailed content of How Can I Access Internal Classes from External Assemblies in C#?. For more information, please follow other related articles on the PHP Chinese website!