C# 反射(Reflection)

反射指程序可以访问、检测和修改它本身状态或行为的一种能力。

程序集包含模块,而模块包含类型,类型又包含成员。反射则提供了封装程序集、模块和类型的对象。

您可以使用反射动态地创建类型的实例,将类型绑定到现有对象,或从现有对象中获取类型。然后,可以调用类型的方法或访问其字段和属性。

优缺点

优点:

  • 1、反射提高了程序的灵活性和扩展性。
  • 2、降低耦合性,提高自适应能力。
  • 3、它允许程序创建和控制任何类的对象,无需提前硬编码目标类。

缺点:

  • 1、性能问题:使用反射基本上是一种解释操作,用于字段和方法接入时要远慢于直接代码。因此反射机制主要应用在对灵活性和拓展性要求很高的系统框架上,普通程序不建议使用。
  • 2、使用反射会模糊程序内部逻辑;程序员希望在源代码中看到程序的逻辑,反射却绕过了源代码的技术,因而会带来维护的问题,反射代码比相应的直接代码更复杂。

以上来自菜鸟教程解释

假如我需要让代码自动识别并执行dll里面所有的方法,这个时候就可以用到c#反射;

1.先用C#写个简单的UI,效果图如下:

代码部分

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms; using System.IO;
using System.Reflection;
using System.Reflection.Emit;
using System.Text.RegularExpressions;
using System.Threading; namespace BojayUI
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
} private void buttonOpenPort_Click(object sender, EventArgs e)
{
this.buttonClosePort.Enabled = true;
this.buttonOpenPort.Enabled = false;
this.buttonOpenProfile.Enabled = true;
//this.buttonBojay.Enabled = true;
MessageBox.Show("OpenPort finish!");
} private void buttonClosePort_Click(object sender, EventArgs e) {
this.buttonClosePort.Enabled = false;
this.buttonOpenPort.Enabled = true;
this.buttonOpenProfile.Enabled = false;
//this.buttonBojay.Enabled = false;
MessageBox.Show("ClosePort finish!");
}
private void buttonOpenFile_Click(object sender, EventArgs e)
{
OpenProfileDialog.InitialDirectory = "C:\\";
OpenProfileDialog.Filter = "Dynamic Link Library (*.dll)|*.dll|Text Document (*.txt)|*.txt|Comma-Separated Values (*.csv)|*.csv|All files (*.*)|*.*";
if (this.OpenProfileDialog.ShowDialog() == DialogResult.OK)
{
this.textBoxProfilePath.Text = OpenProfileDialog.FileName; //save the file……
//system.io.streamreader sr = new system.io.streamreader(openfiledialog1.filename); //this.textbox1.text = sr.readtoend(); //sr.close();
} } private void textBoxProfilePath_TextChanged(object sender, EventArgs e)
{ } private void button_start_Click(object sender, EventArgs e)
{
//******************执行所有类所有函数**************************//
string path = this.textBoxProfilePath.Text; //string path = @"C:\Users\bojay\Desktop\ClassLibrary1\ClassLibrary1\bin\x86\Debug\ClassLibrary1.dll"; //加载dll文件
Assembly asm = Assembly.LoadFile(path); //正则表达式匹配
string pattern = @"\w*\.";
Match match = Regex.Match(path, pattern);
//string[] StrArray_dll = path.Split(new string[] { "\\" }, StringSplitOptions.None);
//string StrArray_namespace = StrArray_dll[StrArray_dll.Length - 1];
//string[] String_class = StrArray_namespace.Split(new string[] { ".dl" }, StringSplitOptions.None); Type[] T = asm.GetTypes();
for (int i = ; i < T.Length; i++)
{
//********************c#****************************
//Type type_1 = asm.GetType(T[i].Name);
//string final_str = String_class[0] + "." + T[i].Name;
string namespace_class = match.Value + T[i].Name; //获取类
Type type = asm.GetType(namespace_class); //创建该类的实例
object obj = Activator.CreateInstance(type); MethodInfo[] methods = type.GetMethods(); try
{
//c#:method.Length-4
//c++:method.Length-5
for (int index = ; index < methods.Length - ; index++)
{
MethodInfo mf = type.GetMethod(methods[index].Name);
mf.Invoke(obj, null);
//**************dll--function return value and parameters***************//
//object result = mf.Invoke(obj, null);
//Console.WriteLine(result);
//ParameterInfo[] para = me.GetParameters();
}
}
catch (Exception ex)
{
throw ex;
} }
//****************************************************************// //****************************************************************//
Type temp_type = asm.GetType(match.Value + T[].Name); object temp_obj = Activator.CreateInstance(temp_type); //FieldInfo[] pi = temp_type.GetFields(); //get min
FieldInfo Minlimit = temp_type.GetField("Minlimit"); string str_min = Minlimit.GetValue(temp_obj).ToString(); //get max
FieldInfo Maxlimit = temp_type.GetField("Maxlimit"); string str_max = Maxlimit.GetValue(temp_obj).ToString(); //scope
this.label_dll1scop.Text = str_min + " < X < " + str_max; //get target data
string line;
using (StreamReader sr = new StreamReader("common.txt"))
{ if ((line = sr.ReadLine()) != null)
{
this.label_dll1Data.Text = line;
}
} int MIN = Convert.ToInt32(str_min);
int MAX = Convert.ToInt32(str_max);
int Target = Convert.ToInt32(line);
if (MIN < Target && Target < MAX)
{
this.label_dll1Result.BackColor = Color.Green;
this.label_dll1Result.Text = "PASS";
}
else
{
this.label_dll1Result.BackColor = Color.Red;
this.label_dll1Result.Text = "Fail";
}
//this.label_dll1scop.Text = "1.0 < X < 100.0";
//this.label_dll1Data.Text = "9.0";
//this.label_dll1Result.BackColor = Color.Green;
//this.label_dll1Result.Text = "PASS";
//Console.ReadKey(); }
}
}

Form1.cs

namespace BojayUI
{
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null; /// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
} #region Windows Form Designer generated code /// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.tabControl1 = new System.Windows.Forms.TabControl();
this.tabPage1 = new System.Windows.Forms.TabPage();
this.buttonOpenProfile = new System.Windows.Forms.Button();
this.textBoxProfilePath = new System.Windows.Forms.TextBox();
this.labelProfilePath = new System.Windows.Forms.Label();
this.buttonClosePort = new System.Windows.Forms.Button();
this.buttonOpenPort = new System.Windows.Forms.Button();
this.tabPage2 = new System.Windows.Forms.TabPage();
this.button_start = new System.Windows.Forms.Button();
this.label_dll1scop = new System.Windows.Forms.Label();
this.label_dll1Data = new System.Windows.Forms.Label();
this.label_dll1Result = new System.Windows.Forms.Label();
this.label_dll1 = new System.Windows.Forms.Label();
this.label1 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.OpenProfileDialog = new System.Windows.Forms.OpenFileDialog();
this.tabControl1.SuspendLayout();
this.tabPage1.SuspendLayout();
this.tabPage2.SuspendLayout();
this.SuspendLayout();
//
// tabControl1
//
this.tabControl1.Controls.Add(this.tabPage1);
this.tabControl1.Controls.Add(this.tabPage2);
this.tabControl1.Location = new System.Drawing.Point(, );
this.tabControl1.Name = "tabControl1";
this.tabControl1.SelectedIndex = ;
this.tabControl1.Size = new System.Drawing.Size(, );
this.tabControl1.TabIndex = ;
//
// tabPage1
//
this.tabPage1.Controls.Add(this.buttonOpenProfile);
this.tabPage1.Controls.Add(this.textBoxProfilePath);
this.tabPage1.Controls.Add(this.labelProfilePath);
this.tabPage1.Controls.Add(this.buttonClosePort);
this.tabPage1.Controls.Add(this.buttonOpenPort);
this.tabPage1.Location = new System.Drawing.Point(, );
this.tabPage1.Name = "tabPage1";
this.tabPage1.Padding = new System.Windows.Forms.Padding();
this.tabPage1.Size = new System.Drawing.Size(, );
this.tabPage1.TabIndex = ;
this.tabPage1.Text = "Setting";
this.tabPage1.UseVisualStyleBackColor = true;
//
// buttonOpenProfile
//
this.buttonOpenProfile.Enabled = false;
this.buttonOpenProfile.Location = new System.Drawing.Point(, );
this.buttonOpenProfile.Name = "buttonOpenProfile";
this.buttonOpenProfile.Size = new System.Drawing.Size(, );
this.buttonOpenProfile.TabIndex = ;
this.buttonOpenProfile.Text = "OpenProfile";
this.buttonOpenProfile.UseVisualStyleBackColor = true;
this.buttonOpenProfile.Click += new System.EventHandler(this.buttonOpenFile_Click);
//
// textBoxProfilePath
//
this.textBoxProfilePath.Location = new System.Drawing.Point(, );
this.textBoxProfilePath.Name = "textBoxProfilePath";
this.textBoxProfilePath.Size = new System.Drawing.Size(, );
this.textBoxProfilePath.TabIndex = ;
this.textBoxProfilePath.TextChanged += new System.EventHandler(this.textBoxProfilePath_TextChanged);
//
// labelProfilePath
//
this.labelProfilePath.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)()))), ((int)(((byte)()))), ((int)(((byte)()))));
this.labelProfilePath.Location = new System.Drawing.Point(, );
this.labelProfilePath.Name = "labelProfilePath";
this.labelProfilePath.Size = new System.Drawing.Size(, );
this.labelProfilePath.TabIndex = ;
this.labelProfilePath.Text = "ProfilePath";
this.labelProfilePath.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
//
// buttonClosePort
//
this.buttonClosePort.Enabled = false;
this.buttonClosePort.Location = new System.Drawing.Point(, );
this.buttonClosePort.Name = "buttonClosePort";
this.buttonClosePort.Size = new System.Drawing.Size(, );
this.buttonClosePort.TabIndex = ;
this.buttonClosePort.Text = "ClosePort";
this.buttonClosePort.UseVisualStyleBackColor = true;
this.buttonClosePort.Click += new System.EventHandler(this.buttonClosePort_Click);
//
// buttonOpenPort
//
this.buttonOpenPort.Location = new System.Drawing.Point(, );
this.buttonOpenPort.Name = "buttonOpenPort";
this.buttonOpenPort.Size = new System.Drawing.Size(, );
this.buttonOpenPort.TabIndex = ;
this.buttonOpenPort.Text = "OpenPort";
this.buttonOpenPort.UseVisualStyleBackColor = true;
this.buttonOpenPort.Click += new System.EventHandler(this.buttonOpenPort_Click);
//
// tabPage2
//
this.tabPage2.Controls.Add(this.button_start);
this.tabPage2.Controls.Add(this.label_dll1scop);
this.tabPage2.Controls.Add(this.label_dll1Data);
this.tabPage2.Controls.Add(this.label_dll1Result);
this.tabPage2.Controls.Add(this.label_dll1);
this.tabPage2.Location = new System.Drawing.Point(, );
this.tabPage2.Name = "tabPage2";
this.tabPage2.Padding = new System.Windows.Forms.Padding();
this.tabPage2.Size = new System.Drawing.Size(, );
this.tabPage2.TabIndex = ;
this.tabPage2.Text = "Work";
this.tabPage2.UseVisualStyleBackColor = true;
//
// button_start
//
this.button_start.Location = new System.Drawing.Point(, );
this.button_start.Name = "button_start";
this.button_start.Size = new System.Drawing.Size(, );
this.button_start.TabIndex = ;
this.button_start.Text = "Start";
this.button_start.UseVisualStyleBackColor = true;
this.button_start.Click += new System.EventHandler(this.button_start_Click);
//
// label_dll1scop
//
this.label_dll1scop.BackColor = System.Drawing.Color.Silver;
this.label_dll1scop.Location = new System.Drawing.Point(, );
this.label_dll1scop.Name = "label_dll1scop";
this.label_dll1scop.Size = new System.Drawing.Size(, );
this.label_dll1scop.TabIndex = ;
this.label_dll1scop.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
//
// label_dll1Data
//
this.label_dll1Data.BackColor = System.Drawing.Color.Silver;
this.label_dll1Data.Location = new System.Drawing.Point(, );
this.label_dll1Data.Name = "label_dll1Data";
this.label_dll1Data.Size = new System.Drawing.Size(, );
this.label_dll1Data.TabIndex = ;
this.label_dll1Data.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
//
// label_dll1Result
//
this.label_dll1Result.BackColor = System.Drawing.Color.Silver;
this.label_dll1Result.Location = new System.Drawing.Point(, );
this.label_dll1Result.Name = "label_dll1Result";
this.label_dll1Result.Size = new System.Drawing.Size(, );
this.label_dll1Result.TabIndex = ;
this.label_dll1Result.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
//
// label_dll1
//
this.label_dll1.BackColor = System.Drawing.Color.Silver;
this.label_dll1.Location = new System.Drawing.Point(, );
this.label_dll1.Name = "label_dll1";
this.label_dll1.Size = new System.Drawing.Size(, );
this.label_dll1.TabIndex = ;
this.label_dll1.Text = "GetValue_FromDll1Text";
this.label_dll1.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
//
// label1
//
this.label1.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)()))), ((int)(((byte)()))), ((int)(((byte)()))));
this.label1.Location = new System.Drawing.Point(, );
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(, );
this.label1.TabIndex = ;
this.label1.Text = "Bojay Common UI V1.0";
this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
//
// label2
//
this.label2.Location = new System.Drawing.Point(, );
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(, );
this.label2.TabIndex = ;
this.label2.Text = "Developed by Tony";
this.label2.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
//
// OpenProfileDialog
//
this.OpenProfileDialog.FileName = "OpenProfileDialog";
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.AutoValidate = System.Windows.Forms.AutoValidate.Disable;
this.ClientSize = new System.Drawing.Size(, );
this.Controls.Add(this.label2);
this.Controls.Add(this.label1);
this.Controls.Add(this.tabControl1);
this.Name = "Form1";
this.Text = "DEMO_UI";
this.tabControl1.ResumeLayout(false);
this.tabPage1.ResumeLayout(false);
this.tabPage1.PerformLayout();
this.tabPage2.ResumeLayout(false);
this.ResumeLayout(false); } #endregion private System.Windows.Forms.TabControl tabControl1;
private System.Windows.Forms.TabPage tabPage1;
private System.Windows.Forms.TabPage tabPage2;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Button buttonOpenPort;
private System.Windows.Forms.Button buttonClosePort;
private System.Windows.Forms.Button buttonOpenProfile;
private System.Windows.Forms.TextBox textBoxProfilePath;
private System.Windows.Forms.Label labelProfilePath;
private System.Windows.Forms.OpenFileDialog OpenProfileDialog;
private System.Windows.Forms.Label label_dll1;
private System.Windows.Forms.Label label_dll1scop;
private System.Windows.Forms.Label label_dll1Data;
private System.Windows.Forms.Label label_dll1Result;
private System.Windows.Forms.Button button_start;
}
}

From1.Designer.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms; namespace BojayUI
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}

Program.cs

2.C#写个dll

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO; namespace ClassLibrary1
{
public class Common
{
public int Maxlimit = ;
public int Minlimit = ;
public int common = ;
}
public class Class1:Common
{
public void WriteFile()
{
int temp = this.common+;
using (StreamWriter sw = new StreamWriter("common.txt"))
{
sw.WriteLine(temp);
}
}
}
}

ClassLibrary1

3.运行UI,加载dll路径

4.执行dll所有类里面的所有方法和属性

5.结果pass,说明该dll里面的函数功能运行结果达到我们的要求;当然啦,这个dll里面只是简单的通过文件写读,将某个目标值进行判断而已,而且我们还需要定义某个公用的类Common,及对应公用属性Maxlimit、Minlimit、common

总结:

<1>dll的C#代码里的namespace命名空间必须和dll文件名一致,因为我们进行匹配的时候只是匹配dll文件名;当然,我们也可以有更好的方法,例如将dll命名空间保持不变,这样我们还不需要对dll路径进行解析

<2>解析字符串的方式可以用正则,也可以用split等较为通俗简便的方法,但可能步骤会稍微多点,建议能用正则还是用正则

<3>dll是用C#写的,可以考虑能否写个.net 平台的C++dll

C#通过反射执行C#dll所有函数的更多相关文章

  1. C# 遍历DLL导出函数

    C#如何去遍历一个由C++或E语言编写的本地DLL导出函数呢 不过在这里我建议对PE一无所知的人 你或许应先补补这方面的知识,我不知道为什么PE方面的 应用在C#中怎么这么少,我查阅过相关 C#的知识 ...

  2. C#反射调用其它DLL的委托事件 传值

    C#反射调用其它DLL的委托事件 传值在插件式开发.我们要调用其它插件或模块的委托事件时.那么我们需要通过反射. 复制代码namespace Module2{ /// <summary> ...

  3. DLL导出函数和类的定义区别 __declspec(dllexport)

    DLL导出函数和类的定义区别 __declspec(dllexport) 是有区别的, 请看 : //定义头文件的使用方,是导出还是导入 #if defined(_DLL_API) #ifndef D ...

  4. 【转】easyui $.message.alert 点击右上角的关闭按钮时,不执行定义的回调函数

    今天發現這個問題 easyui  $.message.alert  点击右上角的关闭按钮时,不执行定义的回调函数

  5. AFX_MANAGE_STATE(AfxGetStaticModuleState())DLL导出函数包含MFC资源

    AFX_MANAGE_STATE(AfxGetStaticModuleState()) 先看一个例子: .创建一个动态链接到MFC DLL的规则DLL,其内部包含一个对话框资源.指定该对话框ID如下: ...

  6. dll 导出函数名的那些事

    dll 导出函数名的那些事 关键字: VC++  DLL  导出函数 经常使用VC6的Dependency或者是Depends工具查看DLL导出函数的名字,会发现有DLL导出函数的名字有时大不相同,导 ...

  7. 动态加载JS文件,并根据JS文件的加载状态来执行自己的回调函数

    动态加载JS文件,并根据JS文件的加载状态来执行自己的回调函数, 在很多场景下,我们需要在动态加载JS文件的时候,根据加载的状态来进行后续的操作,需要在JS加载成功后,执行另一方法,这个方法是依托在加 ...

  8. 关于执行ST_Geometry的st_centroid函数时报ORA-28579错误的问题

    环境 SDE版本:10./10.2/10.2.1/10.2.2 Oracle版本:11g R2 11.2.0.1 Windows版本:Windows Server 2008 R2 问题描述及原因 以全 ...

  9. PDOstament对象执行execute()函数,只要是sql语句正确都是返回true

    [PDO对象操作数据库] PDOstament对象执行execute()函数,只要是sql语句正确都是返回true. 问题: 想要PDO对象实现更改一条记录, 并修改是否成功要返回信息给用户. 上我的 ...

随机推荐

  1. jquery,禁止冒泡和默认行为

    如果在页面中重叠了多个元素,并且重叠的这些元素都绑定了同一个事件,那么就会出现冒泡问题.//HTML 页面<div style="width:200px;height:200px;ba ...

  2. linux每天一小步---awk命令详解

    1 命令功能 awk是linux环境下的一个强大的文本工具,由于awk天生提供对文件中文本分列进行处理,所以如果一个文件中的每行都被特定的分隔符(默认为空格)隔开,我们就可以将这个文件看成是有很多列的 ...

  3. SqlServer 的一个坑

    以前一直以为sqlserver 在做ddl 操作的时候是锁表的,而oracle 是锁行,感觉oracle 要比sqlserver 先进一些,但是这是我的认识错误.其实sqlserver 也是可以锁行的 ...

  4. LINQ to Entity里面不能使用DateTime

    LINQ中不能直接使用DateTime,否则会报错:‘The specified type member 'Date' is not supported in LINQ to Entities. On ...

  5. Visual Studio 2017(VS2017) 企业版 Enterprise 注册码

    Visual Studio 2017(VS2017) 企业版 Enterprise 注册码:NJVYC-BMHX2-G77MM-4XJMR-6Q8QF 终于等到你,最强 IDE Visual Stud ...

  6. Winform嵌入其它应用程序

    Options: using CommandLine; using System; using System.Collections.Generic; using System.Linq; using ...

  7. Mycat SqlServer Do not have slave connection to use, use master connection instead

    Do not have slave connection to use, use master connection instead 很奇怪啊 都是按照配置配置的 怎么就是不通呢 有点怀疑人生了吧 其 ...

  8. Android Dialog 的一些特性

    1. Dialog 与 AlertDialog 的区别. AlertDialog 是一种特殊形式的 Dialog.这个类中,我们可以添加一个,两个或者三个按钮,可以设置标题.所以,当我们想使用 Ale ...

  9. C# 未安装Office环境下使用NPOI导出Excel文件

    1.NuGet直接安装NPOI程序包: 2. using NPOI.XSSF.UserModel; 3.导出Excel代码: private void TsbExport2ExcelClick(obj ...

  10. zTree第二章,各种常见setting设置和方法

    具体详见API文档: http://www.treejs.cn/v3/api.php --------------------------------------------------------- ...