从程序集加载接口并使用其方法

时间:2011-12-27 14:06:05

标签: c# .net reflection interface

我目前正在学习.NET和C#所以我很陌生,我必须创建一个与服务器和客户端的“联系簿”。我创建了一个服务器使用的接口,用于描述此联系簿的可用操作,如下所示:

bool AjouterContact(string num, string nom, string prenom, string mail, string telephone);
bool SupprimerContact(string num);
bool ModifierContact(string num, string nom, string prenom, string mail, string telephone);
List<string[]> RecupererContacts();

我曾经在我的客户端中引用该接口的.dll并且它工作正常,但我现在需要动态加载这个.dll。这就是我正在做的事情:

Assembly a = Assembly.LoadFrom("../../../RemotingInterfaces/bin/Debug/RemotingInterfaces.dll");
Module[] modules = a.GetModules();
Module module = modules[0];
Type[] types = module.GetTypes();
foreach (Type type in types)
{
    Console.WriteLine(" Le type {0} a cette (ces ) methode (s) : ", type.Name);
    Console.WriteLine("Type information for:" + type.FullName);
    Console.WriteLine("\tIs Class = " + type.IsClass);
    Console.WriteLine("\tIs Enum = " + type.IsEnum);
    Console.WriteLine("\tAttributes = " + type.Attributes);
    MethodInfo[] mInfo = type.GetMethods();
    foreach (MethodInfo mi in mInfo)
        Console.WriteLine(" {0}", mi);
}

这适用于控制台中的所有方法。但我想知道如何使用这些方法。

我希望我足够清楚。同样,我是.NET和C#的新手,所以我真的不知道它是如何工作的。

2 个答案:

答案 0 :(得分:3)

接口只是一个契约,它是属性和方法的列表,而不是实际的实现。在您正在使用的DLL中,界面看起来像这样

public interface IJustAListOfThingsToImplement
{
  int GetTheNumberOfStarsInTheSky();
} 

此时方法GetTheNumberOfStarsInTheSky()尚未实现,无法使用。

底线是,您可以获取界面但不能使用它的方法,因为它尚未定义。

希望这有帮助。

答案 1 :(得分:1)

使用MethodInfo.Invoke()使用反射调用方法。在您发布的示例中,您已经在mInfo中存储了一系列方法。

使用Invoke()时,第一个参数是你正在调用方法(即,你正在调用方法的对象),第二个参数是{{对象的3}},表示方法的参数。如果没有参数,您可以传递null