C# reflection calls the external Dll, executes the asynchronous function and takes the return value

using System.Reflection;

 

1. Load Dll

Assembly asm=Assembly.LoadFile(FullPath);//FullPath is the full path where the Dll is located.

2. Get the type of the required class

Type t = asm.GetType( " namespaceName . className " );//Namespace name. Class name

3. Create an object of this type (equivalent to new)

object o = Activator.CreateInstance(t); //Create an object of Type t

4. Get the method you want to execute in the class

MethodInfo me = t.GetMethod("TestFunction");

5. Get the list of parameters required by this method

ParameterInfo[] para=me.GetParameters();

6. Create an object of the parameter type and pass in the parameter Array

Type re = asm.GetType( " TestDll.ReturnClass " ); //My parameter type is the ReturnClass class in the TestDll namespace
 object reo = Activator.CreateInstance(re);
 object [] r = { reo };

7. Call the function

Object rr = me.Invoke(o, r); //If a non-asynchronous function is called, then object rr is the return value of the function.

8. If the call is an asynchronous function

Task task = me.Invoke(o, r) as Task;
 await task;              
 object result = task.GetType().GetProperty( " Result " ).GetValue(task, null ); //result is the return value of the asynchronous function

9. Common operations of reflection

//Get the value of the propertyName property in the o instance value
Type t = asm.GetType( " TestDll.TestClass " ); object o = Activator.CreateInstance(t); object getproperty = t.GetProperty( " propertyName " ).GetValue(o , null ); //Method 1 object getproperty1 = o.GetType().GetProperty( " propertyName " ).GetValue(o, null ); //Method 2

//Get the specified element in the enumeration type
Type enumType = asm. GetType("namespaceName.enumName");
foreach(var name in Enum.GetValues(enumType))
{
   if("elementname"==name.ToString())
   {
Convert.ToInt32(name);//Convert the specified element to int
   }
}
string[] strname=Enum.GetNames(enumType);//Get the names of all elements of the enumeration

10. Summary

Probably, if you don't know the internal structure of Dll, you can get all the information in Dll through reflection

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325951886&siteId=291194637