본문으로 바로가기

동적으로 메서드 실행

category Development/C# 2009. 8. 31. 20:03
다른 클래스의 메서드를 동적으로 실행하는 예제.
우선 네임스페이스 어셈블리를 로드하고, 실행하려는 메서드를 가진 클래스의 인스턴스를 생성한뒤, InvokeMember 함수
를 사용한다. 파라미터도 넘길수 있고, 리턴값도 받을 수 있다.
[Class1.cs]
using System;
public class Class1
{
	public static String method1()
	{
		return "This is static method in class1";
	}
	public String method2()
	{
		return "This is Instance method in class1";
	}
	public String method3( String s )
	{
		return "Hello " + s;
	}
}
[DynaInvoke.cs]
using System;
using System.Reflection;
class DynamicInvoke
{
     public static void Main(String[] args )
    {
           Assembly MyAssembly = Assembly.Load("FirstProject");

           Type MyType = MyAssembly.GetType("FirstProject.Class1");

            object MyObj = Activator.CreateInstance(MyType);

           //Invoking a static method (How to invoke a static method??)   
            String str = (String)MyType.InvokeMember("method1", BindingFlags.Default | BindingFlags.InvokeMethod, null, null, new object[] { });
            Console.WriteLine(str);

            //Invoking a non-static method (How to invoke a non static method??)   
            str = (String)MyType.InvokeMember("method2", BindingFlags.Default | BindingFlags.InvokeMethod, null, MyObj, new object[] { });
            Console.WriteLine(str);

            //Invoking a non-static method with parameters (How to invoke a non static method with parametres??)   
            object[] MyParameter = new object[] { "Sadi" };
            str = (String)MyType.InvokeMember("method3", BindingFlags.Default | BindingFlags.InvokeMethod, null, MyObj, MyParameter);
            Console.WriteLine(str);

	}
}

출처 : http://sadi02.wordpress.com/