문제

인스턴스를 생성하고 기능을 동적으로 실행하는 프로세스를 자동화하려면 어떻게해야합니까?

감사

편집 : 매개 변수를 전달하는 옵션도 필요합니다. 감사

도움이 되었습니까?

해결책

인스턴스를 만들기 위해 매개 변수가없는 생성자를 호출하고 싶습니까? 유형이 문자열로 지정되어 있습니까? 아니면 일반적인 방법으로 만들 수 있습니까? 예를 들어:

// 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);
}

또는

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

다른 팁

생성자를 호출하려면 Activator.CreateInstance 트릭을 할 것입니다. 그것은 당신의 삶을 더 쉽게 만들기 위해 많은 과부하가 있습니다.

생성자 인 경우 매개 변수가 없습니다:

object instance = Activator.CreateInstance(type)

필요한 경우 매개 변수:

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

일단 당신이 유형 당신이 호출 할 수있는 객체 GetMethod 얻기 위해 방법, 그리고 Invoke (매개 변수의 유무에 관계없이) 호출. 필요한 경우 호출이 호출하는 기능의 반환 값 (또는 무효 메소드 인 경우 NULL)을 제공합니다.

약간 더 자세한 샘플 (콘솔 앱에 붙여 넣기) :

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;
        }
    }
}

호출하려는 메소드가 매개 변수를 사용하지 않는다고 가정합니다.

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);
}

나는 당신의 문제가 여기서 너무 일반적이라고 생각합니다. 여기에 특정 가정이있는 솔루션을 제공하고 있습니다.

가정 : typeName (string), MethodName (String) 및 매개 변수 (SomeoneType)가 있습니다.

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 });  
    } 

내 가정이 잘못되었는지 알려주세요.

여기서 매개 변수를 동적으로 전달하기 위해 매개 변수 문자열 [] args를 가져갔습니다. 다른 함수마다 다른 수의 매개 변수가 있기 때문입니다.

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);   

    }
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top