问题
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