創建類庫,並添加新窗體,加入以下方法
public static string setText(string str)
{
return str;
}
編譯后把生成的DLL文件放入新項目的bin目錄,新項目需要using System.Reflection窗口放入2個button,並添加實現
通過反射打開Dll窗體
private void button1_Click(object sender, EventArgs e)
{
//dll命名空間名
string dllName = "DllDemo";
//dll類名
string dllClassName = "DllDemo.Form1";
//載入並創建實例轉為Form類型
Form frm = Assembly.Load(dllName).CreateInstance(dllClassName) as Form;
frm.ShowDialog();
}
通過反射調用Dll中的方法
private void button2_Click(object sender, EventArgs e)
{
//dll文件路徑
string dllName = "DllDemo";
//dll類名
string dllClassName = "DllDemo.Form1";
//加載dll文件
var assembly = Assembly.Load(dllName);
//獲取類
Type type = assembly.GetType(dllClassName);
//創建該類型的實例
object obj = Activator.CreateInstance(type);
//獲取該類的方法
string str = type.InvokeMember("setText", BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Static, null, null, new object[] { textBox1.Text }).ToString();
MessageBox.Show(str);
//縮寫
string returnStr = Assembly.Load(dllName)
.GetType(dllClassName)
.InvokeMember(
"setText"
, BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Static
, null
, null
, new object[] { textBox1.Text } //傳入方法參數
)
.ToString();
MessageBox.Show(returnStr);
}
//網絡素材僅限收藏 方便學習