Vra

Hoe kan ek outomatiseer die proses om 'n geval geskep en sy funksie dinamiese uitgevoer?

Dankie

Edit: Jy het 'n opsie om parameters te slaag. Dankie

Was dit nuttig?

Oplossing

Het jy wil net 'n parameterless constructor bel om die instansie te skep? Is die gespesifiseerde as 'n string sowel tipe, of kan jy dit 'n generiese metode maak? Byvoorbeeld:

// All error checking omitted. In particular, check the results
// of Type.GetType, and make sure you call it with a fully qualified
// type name, including the assembly if it's not in mscorlib or
// the current assembly. The method has to be a public instance
// method with no parameters. (Use BindingFlags with GetMethod
// to change this.)
public void Invoke(string typeName, string methodName)
{
    Type type = Type.GetType(typeName);
    object instance = Activator.CreateInstance(type);
    MethodInfo method = type.GetMethod(methodName);
    method.Invoke(instance, null);
}

of

public void Invoke<T>(string methodName) where T : new()
{
    T instance = new T();
    MethodInfo method = typeof(T).GetMethod(methodName);
    method.Invoke(instance, null);
}

Ander wenke

Om 'n konstruktor te roep, Activator.CreateInstance sal die truuk doen. Dit het 'n klomp van die oorlaai om jou lewe makliker te maak.

As u konstruktor is parameterless :

object instance = Activator.CreateInstance(type)

As jy parameters :

object instance =  Activator.CreateInstance(type, param1, param2)

Om te roep, 'n metode, wanneer jy die Tipe voorwerp wat jy kan bel GetMethod te kry die metode , en dan Invoke (met of sonder parameters) om dit te roep. Indien jy dit nodig het, sal roep ook vir jou die terugkeer waarde van die funksie wat jy noem (of nul as sy 'n leemte metode),

Vir 'n effens meer gedetailleerde monster (plak in 'n konsole app en gaan):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Reflection;

namespace Test
{
    public static class Invoker
    {
        public static object CreateAndInvoke(string typeName, object[] constructorArgs, string methodName, object[] methodArgs)
        {
            Type type = Type.GetType(typeName);
            object instance = Activator.CreateInstance(type, constructorArgs);

            MethodInfo method = type.GetMethod(methodName);
            return method.Invoke(instance, methodArgs);
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            // Default constructor, void method
            Invoker.CreateAndInvoke("Test.Tester", null, "TestMethod", null);

            // Constructor that takes a parameter
            Invoker.CreateAndInvoke("Test.Tester", new[] { "constructorParam" }, "TestMethodUsingValueFromConstructorAndArgs", new object[] { "moo", false });

            // Constructor that takes a parameter, invokes a method with a return value
            string result = (string)Invoker.CreateAndInvoke("Test.Tester", new object[] { "constructorValue" }, "GetContstructorValue", null);
            Console.WriteLine("Expect [constructorValue], got:" + result);

            Console.ReadKey(true);
        }
    }

    public class Tester
    {
        public string _testField;

        public Tester()
        {
        }

        public Tester(string arg)
        {
            _testField = arg;
        }

        public void TestMethod()
        {
            Console.WriteLine("Called TestMethod");
        }

        public void TestMethodWithArg(string arg)
        {
            Console.WriteLine("Called TestMethodWithArg: " + arg);
        }

        public void TestMethodUsingValueFromConstructorAndArgs(string arg, bool arg2)
        {
            Console.WriteLine("Called TestMethodUsingValueFromConstructorAndArg " + arg + " " + arg2 + " " + _testField);
        }

        public string GetContstructorValue()
        {
            return _testField;
        }
    }
}

As ons aanneem dat die metode wat jy wil op te roep nie enige parameters neem nie:

public void InvokeMethod(Type type, string methodName)
{
    object instance = Activator.CreateInstance(type);
    MethodInfo method = type.GetMethod(methodName, BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);

    method.Invoke(instance, null);
}

Ek dink jou probleem is bietjie te generiese hier, ek verskaffing van 'n oplossing met sekere aannames hier.

Assumption: jy het 'n Type Name (string), methodName (string), en 'n parameter (van SomeType)

.
public static void InvokeMethod(string typeName, string methodName, SomeType objSomeType) {
      Type type = Type.GetType(typeName);
      if(type==null) {
        return;
      }
      object instance = Activator.CreateInstance(type); //Type must have a parameter-less contructor, or no contructor.   
      MethodInfo methodInfo =type.GetMethod(methodName, BindingFlags.Instance | BindingFlags.Public);
      if(methodInfo==null) {
        return;
      }
      methodInfo.Invoke(instance, new[] { objSomeType });  
    } 

Laat weet my weet as my aannames verkeerd is.

Om die parameters dinamies te slaag Hier het ek params string [] args geneem, omdat verskillende funksies het verskillende aantal parameters so.

public void Invoke(string typeName,string functionName,params string[] args)
    {

     Type type = Type.GetType(typeName);
     dynamic c=Activator.CreateInstance(type);
     //args contains the parameters(only string type)
     type.InvokeMember(functionName,BindingFlags.InvokeMethod,null,c,args);   

    }
Gelisensieer onder: CC-BY-SA met toeskrywing
Nie verbonde aan StackOverflow
scroll top