c dynamically loads the dll file and invokes the method of recommendation
- 2021-12-04 19:30:12
- OfStack
Here's the test code:
Create a new classlibrary with two classes, class1 and class2, each of which has a method that returns a string. The code is as follows:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace mydll
{
public class Class1
{
public Class1()
{
}
public string sayhello()
{
return "hello,word!";
}
}
public class Class2
{
public Class2()
{
}
public string saybeautiful()
{
return "beautiful,very good!";
}
}
}
After compiling, an mydll. dll dynamic link library will be generated, and then a new winform project will be created (others can also be used for debugging):
private void button1_Click(object sender, EventArgs e)
{
string path = @"D:\123\mydll\mydll\bin\Debug\mydll.dll";
//Byte[] byte1 = System.IO.File.ReadAllBytes(path);// It is also possible
//Assembly assem = Assembly.Load(byte1);
Assembly assem = Assembly.LoadFile(path);
//string t_class = "mydll.Class1";// Theoretically, it has been loaded dll File, you can get the class type by adding the class name to the namespace, which should be modified as follows:
//string t_class = "mydll.Class1,mydll";// If you want to get a class inside this project, you can "namespace" . Parent class... class name " ; If it is external, you need to add " , Link library name " ;
// Thank you again thy38 The help.
//Type ty = Type.GetType(t_class);// When debugging here, ty=null , 1 I don't understand it. I hope someone can solve my doubts
Type[] tys = assem.GetTypes();// I have to get all the type names, and then traverse them and distinguish them by type names
foreach (Type ty in tys)//huoquleiming
{
if (ty.Name == "Class1")
{
ConstructorInfo magicConstructor = ty.GetConstructor(Type.EmptyTypes);// Gets a constructor without arguments
object magicClassObject = magicConstructor.Invoke(new object[] { });// Here is to get 1 Something similar to an instance of a class
//object magicClassObject = Activator.CreateInstance(t);// Obtaining a parameterless construct instance can also be done by
MethodInfo mi = ty.GetMethod("sayhello");
object aa=mi.Invoke(magicClassObject, null);
MessageBox.Show(aa.ToString());// Here is the execution class class1 Adj. sayhello Method
}
if (ty.Name == "Class2")
{
ConstructorInfo magicConstructor = ty.GetConstructor(Type.EmptyTypes);// Gets a constructor that takes no arguments. If there is a constructor and there is no constructor that takes no arguments, this cannot be the case here
object magicClassObject = magicConstructor.Invoke(new object[] { });
MethodInfo mi = ty.GetMethod("saybeautiful");
object aa = mi.Invoke(magicClassObject, null);// Method has parameters, you need to set the null Replace with a collection of parameters
MessageBox.Show(aa.ToString());
}
}
//AppDomain pluginDomain = (pluginInstanceContainer[key] as PluginEntity).PluginDomain;
//if (pluginDomain != null)
//{
// AppDomain.Unload(pluginDomain);
// }
}