Home >Backend Development >C#.Net Tutorial >Detailed explanation of C# dynamic object dynamic implementation methods and attribute dynamic code

Detailed explanation of C# dynamic object dynamic implementation methods and attribute dynamic code

黄舟
黄舟Original
2017-03-21 11:54:451490browse

The following editor will bring you a detailed explanation of C# dynamic objects (dynamic implementation of methods and properties). The editor thinks it is quite good, so I will share it with you now and give it as a reference for everyone. Let's follow the editor and take a look.

C#'s dynamic object properties are relatively simple to implement. If you want to implement dynamic methods like dynamic languages, it is more difficult, because dynamic objects, extension methods, and anonymous methods cannot Use direct methods. Here we still use objects and delegates to simulate the implementation of this dynamic method. It looks like a JavaScript object:

1) Define a delegate , the number of parameters is variable, and the parameters are all of object type: most of the delegates here have a dynamic parameter, which represents the dynamic object itself that calls this delegate.

public delegate object MyDelegate(dynamic Sender, params object[] PMs);

2) Define a delegated reproduction object, because dynamic objects cannot directly use anonymous methods, here we use objects to carry them:

public class DelegateObj
  {
    private MyDelegate _delegate;

    public MyDelegate CallMethod
    {
      get { return _delegate; }
    }
    private DelegateObj(MyDelegate D)
    {
      _delegate = D;
    }
    /// <summary>
    /// 构造委托对象,让它看起来有点javascript定义的味道.
    /// </summary>
    /// <param name="D"></param>
    /// <returns></returns>
    public static DelegateObj Function(MyDelegate D)
    {
      return new DelegateObj(D);
    }
  }

3) Define a dynamic object:

public class DynObj : DynamicObject
  {
    //保存对象动态定义的属性值
    private Dictionary<string, object> _values;
    public DynObj()
    {
      _values = new Dictionary<string, object>();
    }
    /// <summary>
    /// 获取属性值
    /// </summary>
    /// <param name="propertyName"></param>
    /// <returns></returns>
    public object GetPropertyValue(string propertyName)
    {
      if (_values.ContainsKey(propertyName) == true)
      {
        return _values[propertyName];
      }
      return null;
    }
    /// <summary>
    /// 设置属性值
    /// </summary>
    /// <param name="propertyName"></param>
    /// <param name="value"></param>
    public void SetPropertyValue(string propertyName,object value)
    {
      if (_values.ContainsKey(propertyName) == true)
      {
        _values[propertyName] = value;
      }
      else
      {
        _values.Add(propertyName, value);
      }
    }
    /// <summary>
    /// 实现动态对象属性成员访问的方法,得到返回指定属性的值
    /// </summary>
    /// <param name="binder"></param>
    /// <param name="result"></param>
    /// <returns></returns>
    public override bool TryGetMember(GetMemberBinder binder, out object result)
    {
      result = GetPropertyValue(binder.Name);
      return result == null ? false : true;
    }
    /// <summary>
    /// 实现动态对象属性值设置的方法。
    /// </summary>
    /// <param name="binder"></param>
    /// <param name="value"></param>
    /// <returns></returns>
    public override bool TrySetMember(SetMemberBinder binder, object value)
    {
      SetPropertyValue(binder.Name, value);
      return true;
    }
    /// <summary>
    /// 动态对象动态方法调用时执行的实际代码
    /// </summary>
    /// <param name="binder"></param>
    /// <param name="args"></param>
    /// <param name="result"></param>
    /// <returns></returns>
    public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
    {
      var theDelegateObj = GetPropertyValue(binder.Name) as DelegateObj;
      if (theDelegateObj == null || theDelegateObj.CallMethod == null)
      {
        result = null;
        return false;
      }
      result = theDelegateObj.CallMethod(this,args);
      return true;
    }
    public override bool TryInvoke(InvokeBinder binder, object[] args, out object result)
    {
      return base.TryInvoke(binder, args, out result);
    }
  }

Application test code:

dynamic theObj = new DynObj();
      theObj.aaa = "this is a test";//动态属性
      //动态方法,这里不能没法定义参数,调用的时候可以是任意多参数,具体参数类型和含义就只能自己去小心处理了.
      theObj.show = DelegateObj.Function((s, pms) =>
      {
        if (pms != null && pms.Length > 0)
        {
          MessageBox.Show(pms[0].ToString() + ":" + s.aaa);
        }
        else
        {
          MessageBox.Show(s.aaa);
        }
        return null;
      }
      );
      
theObj.show("hello");

Although it looks It sounds a bit like JS defining object methods, but since C# is a static language, the dynamic simulation mechanism provided is still limited. It seems to be dynamic, but all value storage and methods need to be processed by writing your own code.

The above code is tested OK on vs2010, windows 2008 server, and framework 4.0.

The above is the detailed content of Detailed explanation of C# dynamic object dynamic implementation methods and attribute dynamic code. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn