I currently am learning about Reflection
late binding from this video.
And as I replicate the code in the video, there was one part which puzzles me. It is when Invoke
method is used:
MethodInfo getFullNameMethod = customerType.GetMethod("GetFullName");
string[] parameters = new string[2];
parameters[0] = "First";
parameters[1] = "Last";
//here is where I got confused...
string fullName = (string)getFullNameMethod.Invoke(customerInstance, parameters);
As far as I can see (also shown in the video) Invoke
has input parameters of (object, object[])
and has no overloaded method with input parameters (object, object)
.
What being passed here are (object, string[])
. And so, at first I expected that there would be compilation error as I thought string[]
is an object
rather than object[]
. But.... there is no compilation error.
That puzzles me: why string[]
is an object[]
rather than object
(every Type
is C# is derived from object
after all)? Can we not assign string[]
as an object
like this?
object obj = new string[3]; //this is OK
How can a string[]
is both object
and object[]
? Using other data type, say int
, as an analogy, I will never expect a variable as int
and int[]
at the same time.
Can somebody enlighten me?
Here is my full code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Reflection;
namespace ConsoleApplication2 {
class Program {
static void Main(string[] args) {
Assembly executingAssembly = Assembly.GetExecutingAssembly();
Type customerType = executingAssembly.GetType("ConsoleApplication2.Customer");
object customerInstance = Activator.CreateInstance(customerType);
MethodInfo getFullNameMethod = customerType.GetMethod("GetFullName");
string[] parameters = new string[2];
parameters[0] = "First";
parameters[1] = "Last";
string fullName = (string)getFullNameMethod.Invoke(customerInstance, parameters);
Console.WriteLine(fullName);
Console.ReadKey();
}
}
class Customer {
public string GetFullName(string FirstName, string LastName) {
return FirstName + " " + LastName;
}
}
}
Aucun commentaire:
Enregistrer un commentaire