[英]How to call a Managed DLL File in C#?
我正在編寫腳本語言,但是我遇到了嚴重的問題。
我需要這樣做,以便您可以使用該語言調用.NET DLL,但是我發現無法在C#中執行此操作。
有誰知道我如何以編程方式加載和調用.NET dll? (我不能只是添加參考,所以不要這么說)
這是我的操作方式:
Assembly assembly = Assembly.LoadFrom(assemblyName);
System.Type type = assembly.GetType(typeName);
Object o = Activator.CreateInstance(type);
IYourType yourObj = (o as IYourType);
其中assemblyName
和typeName
是字符串,例如:
string assemblyName = @"C:\foo\yourDLL.dll";
string typeName = "YourCompany.YourProject.YourClass";//a fully qualified type name
那么您可以在obj上調用方法:
yourObj.DoSomething(someParameter);
當然,可以調用的方法是由接口IYourType
定義的。
您可以使用Assembly.LoadFrom ,從那里使用標准反射來獲取類型和方法(我假設您已經在腳本中完成了此操作)。 MSDN頁面上的示例(鏈接)顯示以下內容:
Assembly SampleAssembly;
SampleAssembly = Assembly.LoadFrom("c:\\Sample.Assembly.dll");
// Obtain a reference to a method known to exist in assembly.
MethodInfo Method = SampleAssembly.GetTypes()[0].GetMethod("Method1");
// Obtain a reference to the parameters collection of the MethodInfo instance.
ParameterInfo[] Params = Method.GetParameters();
// Display information about method parameters.
// Param = sParam1
// Type = System.String
// Position = 0
// Optional=False
foreach (ParameterInfo Param in Params)
{
Console.WriteLine("Param=" + Param.Name.ToString());
Console.WriteLine(" Type=" + Param.ParameterType.ToString());
Console.WriteLine(" Position=" + Param.Position.ToString());
Console.WriteLine(" Optional=" + Param.IsOptional.ToString());
}
聽起來您需要使用Assembly.Load( MSDN上的Assembly.Load )的重載之一。 動態加載程序集后,可以使用System.Reflection,動態對象和/或接口/基類訪問其中的類型。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.