Feeds:
댓글

Posts Tagged ‘static method’

이 포스팅을 한글로 읽기

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

Read Full Post »