C # Dynamic Object Dynamic implementation method and property Dynamics code explanation

Source: Internet
Author: User
Here's a small section to bring you a C # dynamic object (dynamic) detailed (Implementation methods and properties of the dynamics). Small series feel very good, now share to everyone, also for everyone to make a reference. Let's take a look at it with a little knitting.

C # Dynamic object of the implementation of the property is relatively simple, if you want to implement dynamic language dynamic method is difficult, because for the dynamical object, extension methods, anonymous methods are not direct, here or the use of objects and delegates to simulate the implementation of this dynamic method, Looks like a bit of JavaScript's object flavor:

1) define a delegate with a variable number of arguments, all of which are object types: The delegate here has a dynamic parameter, which represents the object itself that invokes the delegate.

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

2) define a delegate reprint object, because the dynamic object cannot be directly used by anonymous methods, where objects are used to carry:

public class Delegateobj  {    private mydelegate _delegate;    Public MyDelegate callmethod    {      get {return _delegate;}    }    Private Delegateobj (mydelegate D)    {      _delegate = D;    }    <summary>///    construct a delegate object to make it look a bit JavaScript-defined flavor.    </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 {//Save object dynamically defined property value private dictionary<string, object> _values;    Public Dynobj () {_values = new dictionary<string, object> (); }///<summary>//Get property values///</summary>//<param name= "propertyname" ></param>// /<returns></returns> public Object GetPropertyValue (String propertyname) {if (_values.      ContainsKey (propertyname) = = True) {return _values[propertyname];    } return null; }///<summary>//Set attribute values///</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>///To implement the method of dynamic object property member access, get the value of the specified property returned  </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>///To implement Dynamic object property value settings. </summary>//<param name= "binder" ></param>//<param name= "value" ></param>/ <returns></returns> public override bool Trysetmember (SetMemberBinder Binder, Object value) {Se Tpropertyvalue (binder.      Name, value);    return true; }///<summary>///actual code executed when dynamic object dynamic method is called///</summary>//<param name= "Binder" ></param&gt    ; <param name= "args" ></param>//<param name= "result" ></param>//<returns></re turns> 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); }  }

To apply the test code:

Dynamic theobj = new Dynobj ();      THEOBJ.AAA = "This is a test";//Dynamic Properties      //Dynamic methods, here can not be defined parameters, the call may be arbitrary multi-parameter, the specific parameter type and meaning can only be handled with care.      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 like a bit of JS defines the flavor of the object method, but because C # is a static language, the dynamic simulation mechanism provided is still limited and looks dynamic, but all the values are stored and methods need to write their own code to deal with.

The above code is tested OK on Vs2010,windows server, frame 4.0.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.