从 C# 2.0 中的 dll 获取命名空间、类名

发布于 2024-08-08 12:09:18 字数 104 浏览 5 评论 0 原文

我将动态获取dll。我需要加载 dll 并获取命名空间、类名来调用方法(方法名称是静态的,它将始终为“OnStart()”)。 基本上我需要通过加载 dll 来运行一个方法。有人可以帮忙吗!!!

I will get dll's dynamically. I need to load the dll and get the namespace, classname to invoke a method (the method name is static it will be always "OnStart()").
Basically I need to run a method by loading the dll. Can somebody help!!!.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

小苏打饼 2024-08-15 12:09:18

要加载程序集,您可以执行以下操作:

Assembly assembly = Assembly.LoadFile(@"test.dll");

这假设您将程序集作为文件保存在磁盘上。如果不这样做,就像从数据库中以字节数组形式获取它们一样,Assembly 它将帮助您在加载后为您提供一个 Assembly 对象。

要迭代程序集中的所有类,您可以这样做:

Assembly assembly = Assembly.LoadFile(@"test.dll");
foreach (Type type in assembly.GetTypes())
{
    if (type.IsClass)
    {
        ...
    }
}

要查找 OnStart 静态方法,您可以这样做:

Assembly assembly = Assembly.LoadFile(@"test.dll");
foreach (Type type in assembly.GetTypes())
{
    if (type.IsClass)
    {
        MethodInfo method = type.GetMethod("OnStart",
            BindingFlags.Static | BindingFlags.Public);
        if (method != null)
        {
            ...
        }
    }
}

要调用该方法,您可以这样做:

Assembly assembly = Assembly.LoadFile(@"test.dll");
foreach (Type type in assembly.GetTypes())
{
    if (type.IsClass)
    {
        MethodInfo method = type.GetMethod("OnStart",
            BindingFlags.Static | BindingFlags.Public);
        if (method != null)
        {
            method.Invoke(null, new Object[0]); // assumes no parameters
            break; // no need to look for more methods, unless you got multiple?
        }
    }
}

如果需要向该方法传递参数,您可以将它们位于对象数组中:

Object[] arguments = new Object[] { arg1, arg2, arg3 ... };
method.Invoke(null, arguments);

通过使用 Linq 为我们查找方法,可以将上面的代码折叠为以下内容:

Assembly assembly = Assembly.LoadFile(@"test.dll");
var method = (from type in assembly.GetTypes()
              where type.IsClass
              let onStartMethod = type.GetMethod("OnStart",
                  BindingFlags.Static | BindingFlags.Public)
              where onStartMethod != null
              select onStartMethod).FirstOrDefault();
if (method != null)
{
    method.Invoke(null, new Object[0]); // assumes no parameters
}

To load the assembly, you would do this:

Assembly assembly = Assembly.LoadFile(@"test.dll");

This assumes you have the assemblies on disk as files. If you don't, like if you get them from a database as a byte array, there are other methods on the Assembly that will help you give you an Assembly object after loading it.

To iterate through all the classes in the assembly, you would do this:

Assembly assembly = Assembly.LoadFile(@"test.dll");
foreach (Type type in assembly.GetTypes())
{
    if (type.IsClass)
    {
        ...
    }
}

To find the OnStart static method, you would do this:

Assembly assembly = Assembly.LoadFile(@"test.dll");
foreach (Type type in assembly.GetTypes())
{
    if (type.IsClass)
    {
        MethodInfo method = type.GetMethod("OnStart",
            BindingFlags.Static | BindingFlags.Public);
        if (method != null)
        {
            ...
        }
    }
}

To call the method, you would do this:

Assembly assembly = Assembly.LoadFile(@"test.dll");
foreach (Type type in assembly.GetTypes())
{
    if (type.IsClass)
    {
        MethodInfo method = type.GetMethod("OnStart",
            BindingFlags.Static | BindingFlags.Public);
        if (method != null)
        {
            method.Invoke(null, new Object[0]); // assumes no parameters
            break; // no need to look for more methods, unless you got multiple?
        }
    }
}

If you need to pass arguments to the method, you would put them in an object array:

Object[] arguments = new Object[] { arg1, arg2, arg3 ... };
method.Invoke(null, arguments);

The above code can be collapsed to the following by using Linq to find the method for us:

Assembly assembly = Assembly.LoadFile(@"test.dll");
var method = (from type in assembly.GetTypes()
              where type.IsClass
              let onStartMethod = type.GetMethod("OnStart",
                  BindingFlags.Static | BindingFlags.Public)
              where onStartMethod != null
              select onStartMethod).FirstOrDefault();
if (method != null)
{
    method.Invoke(null, new Object[0]); // assumes no parameters
}
携君以终年 2024-08-15 12:09:18
       object result = null;

        using (StreamReader reader = new StreamReader(ASSEMBLYPATH, Encoding.GetEncoding(1252), false))
        {
            byte[] b = new byte[reader.BaseStream.Length];
            reader.BaseStream.Read(b, 0, Convert.ToInt32(reader.BaseStream.Length));
            reader.Close();

            Assembly asm = AppDomain.CurrentDomain.Load(b);
            Type typeClass = asm.GetType(CLASSFULLNAME); // including namespace
            MethodInfo mi = typeClass.GetMethod("OnStart");
            ConstructorInfo ci = typeClass.GetConstructor(Type.EmptyTypes);
            object responder = ci.Invoke(null);

            // set parameters
            object[] parameters = new object[1];
            parameters[0] = null;  // no params


            result = mi.Invoke(responder, parameters);
        }

使用此代码的优点是程序集在使用后被卸载,因此您可以在调用该方法后安全地删除 dll。

       object result = null;

        using (StreamReader reader = new StreamReader(ASSEMBLYPATH, Encoding.GetEncoding(1252), false))
        {
            byte[] b = new byte[reader.BaseStream.Length];
            reader.BaseStream.Read(b, 0, Convert.ToInt32(reader.BaseStream.Length));
            reader.Close();

            Assembly asm = AppDomain.CurrentDomain.Load(b);
            Type typeClass = asm.GetType(CLASSFULLNAME); // including namespace
            MethodInfo mi = typeClass.GetMethod("OnStart");
            ConstructorInfo ci = typeClass.GetConstructor(Type.EmptyTypes);
            object responder = ci.Invoke(null);

            // set parameters
            object[] parameters = new object[1];
            parameters[0] = null;  // no params


            result = mi.Invoke(responder, parameters);
        }

The advantage using this code is that the assembly is unloaded after use, so you can safely delete the dll after invoking the method.

方圜几里 2024-08-15 12:09:18

检查此处: http://dotnetguts .blogspot.com/2008/12/reflection-in-c-list-of-class-name.html

此处用于调用方法:http://www.csharphelp.com/archives/archive200.html

如果您在这些链接中搜索更多术语,您会发现更多信息。

Check here: http://dotnetguts.blogspot.com/2008/12/reflection-in-c-list-of-class-name.html

And here for invoking a method: http://www.csharphelp.com/archives/archive200.html

If you search some more the terms in those links you'll find much more info.

简美 2024-08-15 12:09:18

在运行时,命名空间只是成为类型名称的一部分。

因此,您需要:

  1. 加载程序集
  2. 获取所需类型的 Type 实例。
  3. 获取您要调用的方法的 MethodInfo
  4. 调用该方法。

其中 2-4 项很容易。 1可能容易,也可能不容易,具体取决于装配地点。假设可以通过正常的程序集加载(“探测”)找到程序集。这将调用不带参数但有返回值的类型的公共静态方法。

var asm = Assembly.Load(assemblyName);
var t = asm.GetType(typeName);
// Pass array of parameter types to resolve between overloads (here no arguments).
var m = t.GetMathod(methodName, BindingFlags.Static, null, new Type[] {}, null);
// Pass no "this" or arguments.
var res = (resultType) m.Invoke(null, null);

这里的许多详细信息将取决于您要调用的程序集、类型和方法的详细信息。

At runtime namespaces just become part of the type name.

So you need to:

  1. Load the assembly
  2. Get the Type instance for the type you want.
  3. Get the MethodInfo for the method you want to call.
  4. Call the method.

Of these 2–4 are easy. 1 might be easy or might not, depending where the assembly is. Assuming the assembly can be found via the normal assembly load ("probing"). This will call a public static method of a type that takes no arguments but does have a return value.

var asm = Assembly.Load(assemblyName);
var t = asm.GetType(typeName);
// Pass array of parameter types to resolve between overloads (here no arguments).
var m = t.GetMathod(methodName, BindingFlags.Static, null, new Type[] {}, null);
// Pass no "this" or arguments.
var res = (resultType) m.Invoke(null, null);

A number of the details here will depend on the details of the assembly, type and method you want to call.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文