Assembly.Load in C# Explained
The Assembly.Load method is a method provided by the .NET Framework for loading assemblies. It can load assemblies from different sources such as file paths, file streams, byte arrays, and the display name of the assembly.
The signature of the method is as follows:
public static Assembly Load(string assemblyString)
The parameter assemblyString is a string representing the assembly, which can be the path of the assembly file, a file stream, a byte array, or the display name of the assembly. The display name of the assembly typically includes the fully qualified name of the assembly, which may contain the assembly’s name, version number, culture, and public key information. If assemblyString is a file path, the Load method will load the assembly from the file path; if assemblyString is the display name of the assembly, the Load method will search and load the matching assembly from the global assembly cache or the loading context.
The return value is the loaded assembly object, of type Assembly. After successful loading, subsequent operations can be performed using the returned Assembly object, such as creating instances, calling methods, accessing types and members, etc.
It is important to note that the Load method only loads the assembly and does not execute the code within it. If you need to execute the code in the assembly, you can use the Assembly.GetTypes method to get the types in the assembly, and then create instances or call methods through reflection.
Here is an example code demonstrating how to load and use an assembly using the Assembly.Load method.
// 加载程序集
Assembly assembly = Assembly.Load("MyAssembly");
// 获取程序集中的类型
Type myType = assembly.GetType("MyNamespace.MyClass");
// 创建类型的实例
object instance = Activator.CreateInstance(myType);
// 调用方法
MethodInfo method = myType.GetMethod("MyMethod");
method.Invoke(instance, null);
In conclusion, the Assembly.Load method is an important method used for loading assemblies, which is very useful in scenarios involving dynamically loading and using assemblies. It can load an assembly based on its string representation and return the loaded assembly object for further operations.