C # Common algorithms: Dynamic Object

Source: Internet
Author: User

The Dynamic object is contained in. Net4.0, which allows us to change its type at runtime, with this snake balm. What are the problems we can't solve? Let's take a look at some examples of its use:

var type and dynamic type

public static void Testdynamicobject ()  
{   
    //var object and dynamic Object  
    var varobj = ' This is a var object '; C4/>dynamic Dyobj = "This is a dynamic object";  
      
    Console.WriteLine (varobj);  
    Console.WriteLine (dyobj);  
      
    Dyobj = new string[] {dyobj, "I also can do it liking this!"};  
    Console.WriteLine (Dyobj[0]);  
    Console.WriteLine (Dyobj[1]);  
      
    /*out the ' is ' 
        a var object is a 
        dynamic object 
        I also can do it Liki ng this! 
     */
}

Expandobject

 public static void Testexpandobject () {Dynamic Data = new ExpandoObject (); Data.  
            FirstAttribute = "FirstAttribute"; Data.  
            Secondattribute = "Secondattribute"; Data.  
      
            Thirdattribute = "Thirdattribute";  
            ArrayList nums = new ArrayList (); for (int i = 1; I <= i++) {nums.  
            ADD (i); } data.  
      
            Nums = Nums; foreach (int tmp in data.)  
            Nums) {Console.WriteLine (TMP); } Console.WriteLine (data.  
            FirstAttribute); Console.WriteLine (data.  
            Secondattribute); Console.WriteLine (data.  
      
            Thirdattribute);  
            Action GB = () => {Console.WriteLine ("This was dynamic method."); Data.  
            MYMETHOD2 = GB; Data.  
      
            MYMETHOD2 (); Action<string> ghostbear = a => COnsole.  
            WriteLine (a); Data.  
            MyMethod = Ghostbear; Data. MyMethod ("go! Go!  
      
            Fighting! "); 
                /*out put 1 2 3 4 5 
                6 7 8 9 FirstAttribute 
                Secondattribute Thirdattribute this are dynamic method. Go! Go! 
     
             fighting! */
        }

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.