Dynamic types and double question marks ?? Use

Source: Internet
Author: User

1. The dynamic keyword is used to declare a dynamic object, and then call a method or read/write attribute through the dynamic object. In the past, we used reflection, Emit, CodeDom, and other technologies at runtime. To create a dynamic object, you must use a special builder called ExpandoObject.

Dynamic aehyok = new ExpandoObject (); aehyok. name = "aehyok"; aehyok. age = "24"; aehyok. position = "ASP. NET "; Console. writeLine ("name:" + aehyok. name + "Age:" + aehyok. age + aehyok. position); Console. readKey ();

You can run the program on the console to view the execution result as follows:

 

2. Implement duck typing-based generic parameter constraints through dynamic types.

    public static class Calculator {         public static T Add<T>(T t1, T t2)        {             dynamic d1 = t1;             dynamic d2 = t2;             return (T)(d1 + d2);         }    }

By calling

            int i = Calculator.Add(1, 2);            double d = Calculator.Add(1.1, 2.2);            string s = Calculator.Add("abc", "def");            Console.WriteLine(i + " " + d + " " + s);            Console.ReadKey();

Detected after execution

 

In addition to operator overloading, this method is also applicable to common method calls. This method is a dynamic duck typing generic parameter constraint mechanism that relies on runtime method lookup, which is different from the checking during template compilation, it requires the user to ensure that the input object meets the corresponding requirements.

 

3. The DynamicObject class uses virtual methods to "IMPLEMENT" all methods in the interface. As long as the class is inherited, the reader can dynamically overwrite the method as needed ).

Public class DynamicAnimal: DynamicObject {public override bool TryInvokeMember (InvokeMemberBinder binder, object [] args, out object result) {bool success = base. tryInvokeMember (binder, args, out result); // if the method does not exist, assign the out parameter "result" to null if (! Success) {result = null;} // if this field returns false, an exception is returned. return true ;}}

Inheritance is implemented in a simple way.

Next we create two classes.

Public class Duck: DynamicAnimal {public string Quack () {return "Duck, it's Quack. ";}} Public class Human: DynamicAnimal {public string Talk () {return" humans use Talk instead of Quack ";}}

Call through the console application

Static void Main (string [] args) {var duck = new Duck (); var cow = new Human (); Console. writeLine ("duck is Quack"); Console. writeLine (DoQuack (duck); Console. writeLine ("human is talk"); Console. writeLine (DoQuack (cow); Console. readKey ();} public static string DoQuack (dynamic animal) {string result = animal. quack (); return result ?? "... Of course, humans won't be called ducks ...";}}

Of course, we define a static method below to pass in the dynamic type. here we need to debug it to understand. There is also a double question mark

4. Functions of double question marks:

Double question mark (??) Is a Unit operator, so the data types on both sides must be the same type or can be implicitly converted. It indicates that the value on the left is checked first. If it is Null, the value of the entire expression is the value on the right; otherwise, it is the value on the left.

 

Refer to the following links: C #4.0 and new VS2010 features (3)

 

Sample Code

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.