Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
263 views
in Technique[技术] by (71.8m points)

.net - C# 4: Real-World Example of Dynamic Types

I think I have my brain halfway wrapped around the Dynamic Types concept in C# 4, but can't for the life of me figure out a scenario where I'd actually want to use it.

I'm sure there are many, but I'm just having trouble making the connection as to how I could engineer a solution that is better solved with dynamics as opposed to interfaces, dependency injection, etc.

So, what's a real-world application scenario where dynamic type usage is appropriate?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There are lots of cases where you are already using dynamic typing and dynamic binding today. You just don't realize it, because it is all hidden behind strings or System.Object, since until C# 4, the necessary support wasn't there.

One example is COM interop: COM is actually a semi-dynamic object system. When you do COM interop, a lot of methods actually return a dynamic object, but because C# didn't support them, they were returned as System.Object and you had to cast them yourself, possibly catching exceptions on the way.

Another example is interacting with dynamically typed (or even untyped) data, such as JSON, CSV, HTML, schemaless XML, schemaless web services, schemaless databases (which are, after all, the new hotness). Today, you use strings for those. An XML API would look like

var doc = new XmlDocument("/path/to/file.xml");
var baz = doc.GetElement("foo").GetElement("qux");

and so on. But how about:

dynamic doc = new XmlDocument("/path/to/file.xml");
var baz = doc.foo.qux;

Doesn't that look nice?

A third example is reflection. Today, invocation of a method via reflection is done by passing a string to InvokeMember (or whatever the thing is called). Wouldn't it be nicer to, you know, just invoke the damn thing?

Then, there is generation of dynamic data (basically the opposite of the second example). Here's an example how to generate some dynamic XML:

dynamic doc = new XmlBuilder();
doc.articles(id=42, type="List", () => {
  article(() => {
    number(42);
    title("blahblubb");});});

This is not nearly as beautiful as the equivalent Ruby, but it is the best I could come up with at such short notice :-)

And last but certainly not least, integration with a dynamically typed language. Whether that is JavaScript in a Silverlight application, a custom rules engine embedded in your business app or a DLR instance that you host in your CAD program/IDE/text editor.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...