.NET 动态绑定 TryInvokeMember 详解

从 DynamicObject 类派生的类可以重写此方法,以便为诸如调用方法这样的操作指定动态行为。
结构为
test.Name(parameter) rest:继承DynamicObject 对象 Name动态绑定成员 parameter参数值
代码示例

using System;
using System.Dynamic;
using System.Text;

namespace Test
{

    class Program
    {
        static void Main()
        {
            dynamic d = new Duck();//This Duck inherits the DynamicObject.
            d.Quack(10); // Quack method was called.Name is Quack.Patameter is 10.
            d.Waddle(); // Waddle method was called.Name is Waddle. Parameter is none.
            //When we use the Object.It must trigger the TryInvokeMember method,so we can achieve the customize function.
            Console.ReadKey();
        }
    }
    public class Duck : DynamicObject
    {
        public override bool TryInvokeMember(
        InvokeMemberBinder binder, object[] args, out object result)

        {
            Console.WriteLine(binder.Name + " method was called" + args[0]);//Console the result.
            result = null;
            return true;
        }
    }

}

效果图
在这里插入图片描述

总结:
继承DanymicObject的对象,我们重写它的TryInvokeMember方法,可以直接实现一些我们想要功能,减少重复的代码量。

你可能感兴趣的:(C#,c#,策略模式,开发语言)