CSharp: How do I dynamically call a class(with constructor) and it's methods?
I've been reading examples of Reflection for two days and I can't quite seem to piece together everything to fit what I need. In fact I tho开发者_开发技巧ught I was using reflection, until I noticed my "using System.Reflection" was grayed out. :-)
I have an xml file that contains my class names and the methods contained within. The order of the methods or even the names can change. Once I read them in I want to be able to execute them. Seems simple enough.
I have the following test code:
// myClassName = "namespace.TransactionServices"
Type tb = Type.GetType(myClassName);
// Classes will always have the same constructor
object classInstance = Activator.CreateInstance (
tb,
new object[]
{
authorization.apiKey,
authorization.userName,
testData.servicesEndPoint
});
//Grab the method I want
//myMethodName = "GetVersion"
MethodInfo mymethod = tb.GetMethod(myMethodName);
// no parameters for this method call
object result = mymethod.Invoke(classInstance, null);
tb is null. I was just going to work away at trying to get the correct API for creating the class, but I don't even know if the rest of what I have is valid.
Any suggestions?
Thanks
Edit: Added namespace. Activator.CreateInstance is returning error that constructor is not found.. It is there.
The class name must be fully qualified (including namespace and, most likely, the assembly) in order for it to be resolved. If you know the class is in your current executing assembly, you can use Assembly.GetExecutingAssembly().GetType()
Are you sure you specified the complete class name including namespace? without the namespace, the result will be null.
For GetType you have to provide a fully qualified name. You can get it for an existing object using
MyObject.GetType().AssemblyQualifiedName;
精彩评论