Advantages and Disadvantages of C# 4.0 'dynamic' keyword? [closed]

*爱你&永不变心* 提交于 2020-01-29 05:07:09

问题


I have learned and checked the advantages of dynamic keyword in C# 4.

Can any body tell me the disadvantages of this. Means dynamic vs Var/Object/reflection ???

Which thing is batter more. Is dynamic more powerful at run time??


回答1:


Not exactly var vs dynamic but the following SO link discuss reflection vs dynamic. Check Out : dynamic vs Var/Object/reflection




回答2:


One of the most interesting thing with dynamic keyword which you can do is : implementation of multiple-dispatch.

Here is an example of double-dispatch (a specific case of multiple-dispatch). In OOP, at runtime a particular implementation of virtual (or abstract) method is called, based on the runtime type of one object which is passed as this to the member function. That is called single-dispatch, as the dispatch depends on the runtime type of single object. In double-dispatch, it depends on the type of two objects.

Here is one example:

public abstract class Base {}
public class D1 : Base {}
public class D2 : Base {}
public class D3 : Base {}

public class Test
{
   public static void Main(string[] args)
   {
       Base b1 = new D1();
       Base b2 = new D2();

       Method(b1,b2); //calls 1
       Method(b2,b1); //calls 1: arguments swapped!
   }

   public static void Method(Base b1, Base b2) // #1
   {
        dynamic x = b1;
        dynamic y = b2;

        Method(x,y); // calls 2 or 3: double-dispatch - the magic happens here!

   }
   public static void Method(D1 d1, D2 d2) // #2
   {
       Console.WriteLine("(D1,D2)");
   }
   public static void Method(D2 d2, D1 d1) // #3: parameters swapped 
   {
       Console.WriteLine("(D2,D1)");
   }
}

Output:

(D1,D2)
(D2,D1)

That is, the actual method is selected at runtime, based on the runtime type of two objects, as opposed to one object.



来源:https://stackoverflow.com/questions/8203347/advantages-and-disadvantages-of-c-sharp-4-0-dynamic-keyword

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!