1

我无法掌握各种“Init”、“Accumulate”... 方法的工作原理,以便能够从 VB.Net 代码调用位于 DLL 中的方法。

假设要调用的方法具有以下签名:

public double ComputeMeanPosition(ref SortedList<DateTime, double> posByTime)

请您指出一个使用方法的实际示例,或者简单地给我一些提示,说明如何将参数实际传递给方法,调用它并获取结果?

@Olivier Jacot-Descombes:我肯定会在类名前加上命名空间名称,但无法访问该对象。事实上,我很惊讶您的建议不涉及以下方法,通过对加载的 DLL 的内省显示:

Type: MyClassName
        Method: Void Init()
        Method: Void Accumulate(System.Data.SqlTypes.SqlDouble, System.Data.SqlTypes.SqlDateTime, System.Data.SqlTypes.SqlBoolean)
        Method: Void Merge(MyClassName)
        Method: System.Data.SqlTypes.SqlDouble Terminate()
        Method: Void Write(System.IO.BinaryWriter)
        Method: Void Read(System.IO.BinaryReader)
        Method: Boolean Equals(System.Object)
        Method: Int32 GetHashCode()
        Method: System.String ToString()
        Method: System.Type GetType()

编辑

事实上,我有一个类似于下面的代码,它成功地检查了 DLL 并从中获取了几种类型和方法,为我想调用的方法提供了以下结果。

这是代码

        For Each oneModule As Reflection.Module In useAssembly.GetLoadedModules()
            Console.WriteLine("   - " & oneModule.Name)
            For Each oneType As System.Type In oneModule.GetTypes()
                Console.WriteLine("     Type: " & oneType.Name)
                For Each oneField As Reflection.FieldInfo In oneType.GetFields()
                    Console.WriteLine("        Field: " & oneField.ToString())
                Next oneField

                For Each oneMethod As Reflection.MethodInfo In oneType.GetMethods()
                    Console.WriteLine("        Method: " & oneMethod.ToString())

                    [[ ADD "Invoke" here ?]]
                Next oneMethod
            Next oneType
        Next oneModule

最后,似乎 [[...]] 在应该调用 Invoke 方法以调用我选择的方法的地方,但这就是我卡住的地方......我需要构建调用它之前的对象?我应该如何传递参数?如何得到结果?

4

3 回答 3

7

像这样的东西应该工作:

using System;
using System.Reflection;
using System.IO;

public class MainClass
{
      public static int Main(string[] args)
      {
           Assembly a = null;
           try
           {
                a = Assembly.Load("YourLibraryName");
           }
           catch(FileNotFoundException e)
               {Console.WriteLine(e.Message);}

           Type classType = a.GetType("YourLibraryName.ClassName");

           object obj = Activator.CreateInstance(classType);

           object[] paramArray = new object[1];    
           paramArray[0] = new SortledList<DateTime, double>();
           MethodInfo mi = classType.GetMethod("ComputeMeanPosition");
           mi.Invoke(obj, paramArray);

           return 0;
       }
 }

对于 VB.NET:

Imports System
Imports System.Reflection
Imports System.IO

Public Class MainClass
    Public Shared Function Main(args As String()) As Integer
        Dim a As Assembly = Nothing
        Try
            a = Assembly.Load("YourLibraryName")
        Catch e As FileNotFoundException
            Console.WriteLine(e.Message)
        End Try

        Dim classType As Type = a.[GetType]("YourLibraryName.ClassName")

        Dim obj As Object = Activator.CreateInstance(classType)

        Dim [paramArray] As Object() = New Object(0) {}
        [paramArray](0) = New SortledList(Of DateTime, Double)()
        Dim mi As MethodInfo = classType.GetMethod("ComputeMeanPosition")
        mi.Invoke(obj, [paramArray])

        Return 0
    End Function
End Class

经过测试,这有效:

 Dim a As Assembly = Nothing
    Try
        a = Assembly.Load("TestLib")
    Catch ex As FileNotFoundException
        Console.WriteLine(ex.Message)
    End Try

    Dim classType As Type = a.[GetType]("TestLib.Class1")

    Dim obj As Object = Activator.CreateInstance(classType)

    Dim [paramArray] As Object() = New Object(0) {}
    [paramArray](0) = New SortedList(Of DateTime, Double)()
    Dim mi As MethodInfo = classType.GetMethod("ComputeMeanPosition")
    mi.Invoke(obj, [paramArray])
于 2012-05-04T14:50:57.687 回答
2

这不是实际的代码,因为我不是坐在实际的 c# 编辑器前,而是像这样

// using System.Reflection required

// first load the external assembly into the appdomain and 
// create an instance of the object
var assembly = Assembly.Load("Path to the Assembly");
var type = assembley.GetType("TheNameOfTheClass");
var ctor = type.GetConstuctor();
var object = ctor.Invoke(); // assuming an empty construtor, else you'll need to pass in data

// next invoke the method
var methodInfo = assembly.GetMethodByName("ComputeMeanPosition");
var param = new SortedList<DateTime, double>();
var result = methodInfo.Invoke(object, new object[] { param });
于 2012-05-04T14:45:38.650 回答
1

您可以像在 VB 中这样声明一样调用此方法

Public Function ComputeMeanPosition( _
    ByRef posByTime As SortedList(Of DateTime, Double)) As Double

注意:我使用这个在线片段转换器将 C# 代码转换为 VB。{}在转换之前,您必须将一个空的方法主体添加到 C# 方法标头。

public double ComputeMeanPosition(ref SortedList<DateTime, double> posByTime) {}

由于此方法未static在 C# 中(Shared在 VB 中)中声明,因此您首先需要创建一个对象。该方法很可能在类中声明。假设这个类被命名为“MyClass”,那么你将不得不写这样的东西

Dim posByTime = New SortedList(Of DateTime, Double)()
Dim obj = New MyClass()
Dim result As Double = obj.ComputeMeanPosition(posByTime)

如果构造函数(New方法)声明了参数,则必须在创建对象时传递它们

Dim obj = New MyClass(arg1, arg2, ...)

根据ComputeMeanPosition预期,您必须posByTime在调用它之前将项目添加到列表中。


如果该方法是static在 C# 中(Shared在 VB 中)声明的,您将使用类名来限定它,而不是创建一个对象。

Dim posByTime = New SortedList(Of DateTime, Double)()
Dim result As Double = MyClass.ComputeMeanPosition(posByTime)

更新

如果你动态加载程序集,你可能会做这样的事情

Dim ass As Assembly = Assembly.LoadFrom("C:\SomePath\MyDll.dll")
Dim obj As Object = ass.CreateInstance("MyClass", True) 

Dim posByTime = New SortedList(Of DateTime, Double)()
Dim result As Double = obj.ComputeMeanPosition(posByTime)

而且您必须设置Option Strict Off后期绑定。


如果构造函数需要参数,则必须将它们传递给另一个重载CreateInstance

Dim args = new Object() { arg1, arg2, ... }
Dim obj As Object = ass.CreateInstance("MyClass", True, _
    BindingFlags.Public Or BindingFlags.Instance, Nothing, Nothing, _
    args, Nothing, Nothing)
于 2012-05-04T14:44:11.487 回答