Reputation: 12949
I'm currently studying .NET and C# so I'm pretty new to it and I have to create a 'contact book' with a server and a client. I created an interface used by the server that describes the operations available for this contact book like below:
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();
I used to refer to the .dll of that interface in my client and it worked fine, but I now need to load this .dll all dynamically. This is what I'm doing :
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);
}
This works and writes all the methods in the console. But I would like to know how to use these methods.
I hope I was clear enough. Again, I'm new to .NET and C# so I don't really know how it works.
Upvotes: 1
Views: 1164
Reputation: 37516
Use MethodInfo.Invoke() to call a method using reflection. In your example you posted, you already have an array of the methods stored in mInfo
.
When using Invoke()
, the first argument is who you are invoking the method on (i.e., which object you are invoking the method on), and the second argument is a params array of object, which denote the parameters to the method. If there are no arguments, you may pass null
.
Upvotes: 1
Reputation: 14944
The interface is just a contract, it's a list of properties and methods and not actual implementation. The interface looks something like this in the dll you are working with
public interface IJustAListOfThingsToImplement
{
int GetTheNumberOfStarsInTheSky();
}
At this point the method GetTheNumberOfStarsInTheSky() is not implemented yet and cannot be used.
Bottom line is, you can get the interface but you cannot use it's methods because it's not defined yet.
Hope this helps.
Upvotes: 3