I've been looking around at various examples of Reflections and couldn't find any that go into detail about the scenario i need.

Let me explain what my current situation is:

Main Console App (passes down a string to Class A)
-> Class A which sole purpose is to take the string from Main Console App, and use it to convert to a specific type.
-> Class B/C/D/E/F/G/etc... These classes all serve one purpose as well, which is to run an executed plan. Class A needs to determine, based on a string from the Main Console App, which instance of these classes to make an instance of, and act upon it. Reflection seems like what I need, i just couldnt find a way to create an insatnce of type 'x', based on what string is passed down from main console app to class A.
-> Class Base -> classes B-Z derive from class Base. Shouldn't really affect the actual question here though, which is about Reflection and the syntax needed to convert to a specific type, based on a string.

from what i've read so far, im going to need to use:

public void RunClass(string className)
     Assembly assemb = Assembly.SomewayToGetCurrentAssembly; 
     SomeObject = assemb.CreateInstance(ofTypeNeededBasedOnSTring) as Something?; 
     //... MethodInfo meth = SomeObject.GetMethod("ExecuteTask");

Hope this is enough information to get my point across.


So I got most of it working - Here's what i'm doing now. I just need some direction/assistance on one line, which is the MethodInfo object.Invoke method.

public void RunScript(string scriptName)
            Assembly _assemblyInfo = Assembly.LoadFrom(scriptName);
            Type[] types = _assemblyInfo.GetTypes();
            Type temp = null;
            foreach (Type t in types)
                if (t.FullName == "Scripting.Test.Autosniff")
                    Console.Write("this may actually work\n");
                    temp = t;
            MethodInfo meth;
            meth = temp.GetMethod("RunScript");
            meth.Invoke(???, null);

I've tried passing temp into the first parameter of Invoke, but it fails saying it's of a different type than needed.
BTW, the RunScrpt Method is:

public override void RunScript()
            x = 5;
            y = 10;
            z = 15;

Just some placeholder stuff to get the method invoke working.

Figured it out

public void RunScript(string scriptName)        
Assembly _assemblyInfo = Assembly.LoadFrom("Script.dll");            
Type theType = _assemblyInfo.GetType(scriptName);      
MethodInfo meth;            
meth = theType.GetMethod("ExecuteScript");           
object obj = Activator.CreateInstance(theType);            
meth.Invoke(obj, null);        
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.