开发者

What is the intent of dynamics in C# 4.0? What are some "neat" uses of it?

Just as the title states... is it primarily for instances where you don't know precisely what type will be returned from a method call (CO开发者_如何学CM interop maybe)?


Here is an example that i consider a nice improvement, it doesn't change a great deal, but it's the little things in life that make a difference :)

http://weblogs.asp.net/gunnarpeipman/archive/2010/07/27/asp-net-mvc-3-new-viewmodel-is-dynamic-viewdata.aspx


As you mention, it makes it easier to interoperate with dynamic languages.

For me, that usually means javascript. One of my favorite uses is consuming JSON on the server without defining DTOs - which also enables LINQ to JSON:

JsonObject body;
string[] favoriteToys =
  (from child in (JsonValue)body.AsDynamic().Children
   where child.Value.AsDynamic().Name.ReadAs<string>(string.Empty).StartsWith("J")
   select child.Value.AsDynamic().BestToy.ReadAs<string>("No favorite toy"))
       .ToArray();

(Sample code lifted from "Okay, WCF, we can be friends now", and be sure to see "WCF support for jQuery on wcf.codeplex.com")


If you didn't exactly know the type of a variable, or you wanted to allow the user to specify a class to load at runtime and use the C# reflection API to load it, then you could use dynamic typing so that the user does not need their class to derive from anything, but just needs to define certain methods (an exception would be thrown if not and an error printed from the exception to tell the user what happened).

The advantage of this is that there would be less typing by the user, and therefore less space for user error.


They are useful in scenarios where you don't know the return type, or you don't know at compile-time what members will be available on an object, so you can defer it until run-time. Another neat use of dynamic is ExpandoObject. This allows you to added members to an object at run-time. I've used it to replace Dictionary<string, object> style code.


Yes, COM interop is probably the most common place where dynamics will be incredibly useful. I've used it in conjunction with IronPython to make calls to python methods (which are dynamic scripts by nature) much cleaner and easier. These are the kinds of things it was intended for.

That said, the overall effect of introducing dynamics is to enable C# to become a kind of scripting language, and there is a strong likelihood that it will be used for a number of other purposes along those lines (much to the horror of language purists). For example, the ViewBag property in MVC 3 is just a dynamic wrapper for the ViewData collection. It makes syntax look just a tad "cleaner" (ViewBag.FirstName instead of ViewData["FirstName"]), but at the potential cost of clarity: At a glance, a C# developer might assume that the former is an access to a property on a strongly-typed object of some kind, which can give them a false sense of security when there are no compiler errors.

I've also heard of frameworks that can deserialize a JSON string into a dynamic object, so your .NET system could handle dynamic javascript objects from AJAX requests in much the same way javascript handles them. It's really cool to some people and at least a little creepy to others.


one of the "cool" things you get with dynamic is multiple dispatch without the visitor pattern.

public class Fruit {}
public class Apple : Fruit {}

public class GrannySmith : Apple {}


public class FruitSalad
{
    public void Mix(Apple apple) {
        Console.WriteLine("mixing a apple");
    }

    public void Mix(GrannySmith apple) {
        Console.WriteLine("mixing a Granny-Smith apple");
    }

    public void Mix(Fruit fruit) {
        Console.WriteLine("unknown fruit, can't mix!");
    }

}

    public static void Main(string[] args)
    {
        var salad = new FruitSalad();

        Fruit fruit = new Apple();
        salad.Mix(fruit); // unknown fruit, can't mix 
                          // (can't resolve onm the type of parameter)

        dynamic fruit2 = new Apple();
        salad.Mix(fruit2); // mixing a apple
                           // with dynamic, the parameter's resolution 
                           // is deferred to runtime, so now we know it's an apple

    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜