当前位置:网站首页>Reflection principle and application in C #
Reflection principle and application in C #
2022-06-09 02:37:00 【God of Luo Xiu】
Let's take a look at a picture

Reverse engineering , You can put Dll/Exe Decompile the file ,IL Is a reference to C# The code of the code ,metadata Is a list of data , Record what it contains, not the details of the implementation ;
1. The principle of reflection :
Reflection is System.Reflection Namespace , Can read metadata, And use metadata, It is a help class provided by Microsoft , It is used in all scenarios , And its main function is “ decoupling ”, Reduce reliance on details .
The simple understanding is , When C# When the code is compiled , The classes and methods in the project will be recorded in metadata Inside , And then use it System.reflection Can read metadata Recorded information , Thus, you can get the corresponding type and all class methods according to the instance of the type .
Next is the application , Look at the code below
scene 1
By getting an example of Type, And then use this Type To generate a new instance
namespace ConsoleApp1
{
class Class1
{
public void Fun(int a, int b)
{
int res = a + b;
Console.WriteLine($"Fun res is {
res}");
}
public int val = 10;
}
static void Main(string[] args)
{
Class1 class_a = new Class1();
Type a_type = class_a.GetType();
dynamic aa = Activator.CreateInstance(a_type); // Dynamically create a new class instance based on a class type
Console.WriteLine(aa.GetType()); // The output is zero ConsoleApp1.Class1
Console.WriteLine(aa.val); // 10
}
}
scene 2
establish dll Examples in , This is just for convenience , Generate solutions from the above projects , In its bin There will be corresponding in the directory dll file , The code is as follows :
static void Main(string[] args)
{
// The absolute path here , Find your previously generated dll file
Assembly assembly = Assembly.LoadFrom("E:/study_file/Pracfile/CStest1/ConsoleApp1/bin/Debug/netcoreapp3.1/ConsoleApp1.dll");
Type cur_type = assembly.GetType("ConsoleApp1.Class1");
dynamic cur_obj = Activator.CreateInstance(cur_type);
Console.WriteLine($"res is : {
cur_obj.GetType()}"); // res is : ConsoleApp1.Class1
}
Here, the generation is based on the type obtained , Two examples of generating instances , The following describes how to get the corresponding type methods and their calls . The code is as follows :
namespace ConsoleApp1
{
class Class1
{
public void Fun(int a, int b)
{
int res = a + b;
Console.WriteLine($"a = {
a} b = {
b}");
}
public void Fun(int a, int b, int c) // heavy load
{
int res = a + b;
Console.WriteLine($"a = {
a} b = {
b} c = {
c}");
}
public int val = 10;
}
static void Main(string[] args)
{
Assembly assembly = Assembly.LoadFrom("E:/study_file/Pracfile/CStest1/ConsoleApp1/bin/Debug/netcoreapp3.1/ConsoleApp1.dll");// The absolute path here , Find your previously generated dll file
Type cur_type = assembly.GetType("ConsoleApp1.Class1");
dynamic cur_obj = Activator.CreateInstance(cur_type);// Generate instances
// According to the function name , And parameter list Type Type to get the corresponding function , The access is saved in metadata Data information in
MethodInfo methodInfo_a = cur_type.GetMethod("Fun",new Type[] {
typeof(int), typeof(int)});
methodInfo_a?.Invoke(cur_obj, new object[] {
3, 5 });
MethodInfo methodInfo_b = cur_type.GetMethod("Fun", new Type[] {
typeof(int), typeof(int), typeof(int) });
methodInfo_b?.Invoke(cur_obj, new object[] {
3, 5, 7 }); // Call the corresponding function
}
}
There are also some commonly used function interfaces , Also simply record
namespace ConsoleApp1
{
class Class1
{
private void Test()
{
Console.WriteLine($"this is pricate Test !!!");
}
public void Fun(int a, int b)
{
int res = a + b;
Console.WriteLine($"a = {
a} b = {
b}");
}
public void Fun(int a, int b, int c)
{
int res = a + b;
Console.WriteLine($"a = {
a} b = {
b} c = {
c}");
}
public int val = 10;
}
class Program
{
static void Main(string[] args)
{
Assembly assembly = Assembly.LoadFrom("E:/study_file/Pracfile/CStest1/ConsoleApp1/bin/Debug/netcoreapp3.1/ConsoleApp1.dll");// The absolute path here , Find your previously generated dll file
Type cur_type = assembly.GetType("ConsoleApp1.Class1");
dynamic cur_obj = Activator.CreateInstance(cur_type);
// Get a list of all the functions
MethodInfo[] methodInfos = cur_type.GetMethods();
foreach(MethodInfo m in methodInfos)
{
}
// Get a single function
MethodInfo methodInfo_a = cur_type.GetMethod("Fun", new Type[] {
typeof(int), typeof(int), typeof(int) });
methodInfo_a?.Invoke(cur_obj, new object[] {
1,2,3});
// use BindingFlags Mark the function range obtained The range represented here is the non-public function in the instance (private protect internal)
MethodInfo methodInfo_b = cur_type.GetMethod("Test", BindingFlags.Instance | BindingFlags.NonPublic);
methodInfo_b?.Invoke(cur_obj, null); // this is pricate Test !!! Private functions can be called directly here , Isn't that amazing
}
}
}
边栏推荐
- Embracing out of hospital prescription drugs, Internet medicine should also "get rid of virtual reality"?
- 【HomeAssistant外网访问(cpolar)】
- Jedis工具类、适配单个redis以及redis集群
- [coding streaming] installation and use of SRS streaming media server
- Mysql database connection query join principle
- 技术负责人如何搞垮一个团队?
- Indonesia widya robotics and Huawei cloud make the safety of construction sites visible
- Docker安装Redis
- Rk3399 platform development series explanation (Introduction to kernel) 1.52. Call stack analysis of probe function in platform
- C classes and objects
猜你喜欢

Go to MFC from Win32

Interface test series - interface test practice of transfer transaction business scenarios

How does the technical leader bring down a team?

Summary of 14 anomaly detection methods

【HomeAssistant外网访问(cpolar)】
How to implement the project practice of user registration, login and logout in flask + MySQL

toggleRowSelection()失效的2個重要影響因素

Blue Bridge Cup_ Multiple problem_ stack_ Remainder
![[network protocol] | [01] network byte order big end and small end](/img/9f/c69293aa8983161f4733a84389a311.png)
[network protocol] | [01] network byte order big end and small end

Unity中,继承MonoBehaviour游戏对象的生命周期
随机推荐
Using redis in business code to achieve caching effect
String 3-387. 字符串中的第一个唯一字符
Implementation of UESTC daily report based on Selenium
LeetCode 1155. 掷骰子的N种方法**
Discussion on MLIR Technology
ClassNotFoundException vs NoClassDefFoundError
Processes and threads
杰理之AD 值的硬件计算原理?【篇】
21. Class E power amplifier design of ads usage record (medium)
(10.3)【隐写缓解】隐写防护、隐写干扰、隐写检测
Gunicorn 20.0.4 request smuggling vulnerability
杰理之若用户不需要使用所有的按键,其他按键应该如何设置?【篇】
FFmpeg的软、硬解码方式梳理
What are the focuses of testing, pre release and production environment testing?
技术负责人如何搞垮一个团队?
Sectigo证书价格
Rk3399 platform development series explanation (Introduction to kernel) 1.52. Call stack analysis of probe function in platform
PHP replicated vulnerability
Unity中,继承MonoBehaviour游戏对象的生命周期
数据库表无法添加内容显示修改无法保存提示1452错误