다른 클래스의 메서드를 동적으로 실행하는 예제.
우선 네임스페이스 어셈블리를 로드하고, 실행하려는 메서드를 가진 클래스의 인스턴스를 생성한뒤, 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/
'Development > C#' 카테고리의 다른 글
| 월중 첫날짜, 마지막날짜 구하기 (0) | 2009.09.01 |
|---|---|
| 레퍼런스(Reference) 변수를 ref 인자로 넘겨주는 이유 (0) | 2009.09.01 |
| Custom ToolStrip, MenuStrip Demo (0) | 2009.08.31 |
| 네트워크 드라이브 연결하기 (0) | 2009.08.27 |
| UTC 시차 극복 방법 (0) | 2009.08.27 |