C# 加载程序集并运行方法

C# 加载程序集并运行方法,c#,reflection,C#,Reflection,我想加载一个程序集(dll test.dll),并运行方法GetLabel: namespace Dlltest.Test { public class Main { public string GetLabel() { string test = "TestString"; return test; } } } Assembly assembly = Assembly.Lo

我想加载一个程序集(
dll test.dll
),并运行方法
GetLabel

namespace Dlltest.Test
{
    public class Main
    {
        public string GetLabel()
        {
            string test = "TestString";
            return test;
        }
    }
}
Assembly assembly = Assembly.LoadFile(@"C:\dll-test.dll");
Type type = assembly.GetType();
var obj = Activator.CreateInstance(type);

var result = type.InvokeMember("GetLabel",
                              BindingFlags.Default | BindingFlags.InvokeMethod,
                              null,
                              obj,
                              null);

MessageBox.Show(result.ToString);
我有以下代码,但无法运行
GetLabel

namespace Dlltest.Test
{
    public class Main
    {
        public string GetLabel()
        {
            string test = "TestString";
            return test;
        }
    }
}
Assembly assembly = Assembly.LoadFile(@"C:\dll-test.dll");
Type type = assembly.GetType();
var obj = Activator.CreateInstance(type);

var result = type.InvokeMember("GetLabel",
                              BindingFlags.Default | BindingFlags.InvokeMethod,
                              null,
                              obj,
                              null);

MessageBox.Show(result.ToString);
它应该显示一个带有
TestString
的消息框

编辑

我最终与以下人员合作:

Assembly assembly = Assembly.LoadFile(@"C:\dll-test.dll");
var type = assembly.GetTypes();
var obj = Activator.CreateInstance(type[0]);

var result = type[0].InvokeMember("GetLabel",
                          BindingFlags.Default | BindingFlags.InvokeMethod,
                          null,
                          obj,
                          null);

MessageBox.Show(result.ToString());
一致

Type type = assembly.GetType();
您分配的是
程序集
变量的类型,而不是所需的类型。尝试
assembly.GetType(type\u name)
。此外,将“GetGabel”更改为“GetLabel”:)

在第行

Type type = assembly.GetType();
您分配的是
程序集
变量的类型,而不是所需的类型。尝试
assembly.GetType(type\u name)
。此外,将“GetGabel”改为“GetLabel”:)

试试看

Type type = assembly.GetType("MyType");
if(temp == null) throw new InvalidOperationException();
//...
试一试


这将创建System.Reflection.Assembly的实例并调用它的GetGabel方法…这将创建System.Reflection.Assembly的实例并调用它的GetGabel方法…Visual Studio向我提供以下错误:
参数1:无法将messagebox的“方法组”转换为“字符串”
。您忘记了中的括号
result.ToString()
:)啊,谢谢!我还编辑了我的主要帖子(完整的工作代码)。Visual Studio给了我以下错误:
参数1:无法将messagebox的“方法组”转换为“字符串”
。您忘记了
result.ToString()
:)啊,谢谢!我还编辑了我的主要帖子(完整的工作代码)。Visual Studio给了我以下错误:
参数1:无法将messagebox的“方法组”转换为“字符串”
。请使用
messagebox.Show(result.ToString())
(需要调用该方法,而不是传递它的“引用”)Visual Studio向我提供了以下错误:
参数1:无法将messagebox的“方法组”转换为“字符串”
。请使用
messagebox.Show(result.ToString())
(需要调用该方法,而不是传递其“引用”)