夜光带你走进C#反射(二十)擅长的领域

mac2024-04-11  42

夜光序言:

 

 申请进入你的心里,我敲门了喔。

 

 

 

 

 

 

 

 

 

 

正文:

 

 

 

 

 

 

 

using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Reflection; //反射的使用 namespace WindowsFormsApp1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { //现在,我们是写死的,但是实际开发过程中我们是不写死的 string dllName = "MyClassLibrary"; //夜光:指定dll文件的名字,或者程序集的名字 string fullName = "MyClassLibrary.YunSuan"; Assembly assembly = Assembly.Load(dllName); //程序集加载 Type type = assembly.GetType(fullName); //从程序集中获取指定对象的类型 var dll = Activator.CreateInstance(type); //创建构造函数 //调用程序集中的方法 string jiafa = type.InvokeMember("JiaFa", BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Static, null, null, new object[] {textBox1.Text.Trim()}).ToString(); MessageBox.Show(jiafa); } } }

 

 

 

using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Reflection; //反射的使用 namespace WindowsFormsApp1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { //现在,我们是写死的,但是实际开发过程中我们是不写死的 string dllName = "MyClassLibrary"; //夜光:指定dll文件的名字,或者程序集的名字 string fullName = "MyClassLibrary.YunSuan"; Assembly assembly = Assembly.Load(dllName); //程序集加载 Type type = assembly.GetType(fullName); //从程序集中获取指定对象的类型 var dll = Activator.CreateInstance(type); //创建构造函数 //调用程序集中的方法 string jiafa = type.InvokeMember("JiaFa", BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Static, null, null, new object[] {textBox1.Text.Trim()}).ToString(); MessageBox.Show(jiafa); } private void abc() { //隐式类型 //.net 3.0以后才开始引入的 //夜光:编译器可以自动判断数据类型 /* * 使用规则 1.var类型的值必须是局部变量或者是静态变量 2.声明的时候必须被初始化 赋值 3.变量的值不能是null 4.不能声明为一个方法或者一个方法组 5.不能用来作为方法的参数 */ var name = "Genius Team"; var age = 18; var flag = false; } private void button2_Click(object sender, EventArgs e) { abc(); } } }

 

 

 

 

 

 

最新回复(0)