C # 4.0 - calls a protected method call when a dynamic object TryInvokeMember () is called?

C # 4.0 introduces a new DynamicObject.

It provides a "magic method" TryInvokeMember (), which is called when trying to call a method that does not exist.

http://msdn.microsoft.com/en-us/library/system.dynamic.dynamicobject.tryinvokemember%28VS.100%29.aspx

What I would like to know is to call TryInvokeMember () when trying to call a protected method outside the class.

I compare the behavior with PHP, which in this situation calls its equivalent "magic method" __call ().

+5
source share
1 answer

, , ( #), , TryInvokeMember ( ). , :

class Test : DynamicObject {
  public void Foo() {
    Console.WriteLine("Foo called");
  }
  protected void Bar() {
    Console.WriteLine("Bar called");
  }

  public override bool TryInvokeMember
      (InvokeMemberBinder binder, object[] args, out object result) {
    Console.WriteLine("Calling: " + binder.Name);
    return base.TryInvokeMember(binder, args, out result);
  }
}

:

dynamic d = new Test();
d.Foo(); // this will call 'Foo' directly (without calling 'TryInvokeMember')
d.Bar(); // this will call 'TryInvokeMember' and then throw exception

, base TryInvokeMember, # , TryInvokeMember ( result true).

+6

All Articles