Feeds:
댓글

Posts Tagged ‘dynamic’

이 포스팅을 한글로 읽기

Let me write down some codes regarding doing some thing in dynamic ways.

  • Change type of an object
object obj = something;
Type new_type = something;

Convert.ChangeType(obj, new_type)
  • Invoke a member variable of an instance dynamically
Type instance_type = something;
string variable_name = something;
object instance = something;

object value = instance_type.InvokeMember(variable_name, BindingFlags.Default | BindingFlags.GetProperty, null, instance, null);
  • Invoke a method of an instance dynamically (1)
object instance = something;  // set null if want to use a static method.
Type instance_type = something;
string method_name = something;
object[] args = object[xx] () = { xx, xx, xx, xx }; // could be null

object return_value = instance_type.InvokeMember(method_name, BindingFlags.Default | BindingFlags.InvokeMethod, null, instance, args);
  • Invoke a method of an instance dynamically (2)
object instance = something;
string method_name = something;
object [] args = new object[xx] { xx, xx, xx, xx };  // could be null

Type instance_type = instance.GetType();
MethodInfo method = instance_type.GetMethod(method_name);
object return_value = method.Invoke(instance, args);

Read Full Post »

Read this article in English.

뭘 좀 만들다가 쓰게 된 것들, 한 번 살짝만 정리해봅니다^^

  • object 의 type 바꾸기
object obj = something;
Type new_type = something;

Convert.ChangeType(obj, new_type)
  • 동적으로 인스턴스의 멤버 변수 값 얻어오기
Type instance_type = something;
string variable_name = something;
object instance = something;

object value = instance_type.InvokeMember(variable_name, BindingFlags.Default | BindingFlags.GetProperty, null, instance, null);
  • 동적으로 인스턴스의 메소드 실행하기 1
object instance = something;  // static method 일 경우에 instance 값을 null로 한다
Type instance_type = something;
string method_name = something;
object[] args = object[xx] () = { xx, xx, xx, xx }; // could be null

object return_value = instance_type.InvokeMember(method_name, BindingFlags.Default | BindingFlags.InvokeMethod, null, instance, args);
  • 동적으로 인스턴스의 메소드 실행하기2
object instance = something;
string method_name = something;
object [] args = new object[xx] { xx, xx, xx, xx };  // could be null

Type instance_type = instance.GetType();
MethodInfo method = instance_type.GetMethod(method_name);
object return_value = method.Invoke(instance, args);

Read Full Post »