开发者

Most common applications of the C# 4.0 dynamic type

Now that people have been using C# 4.0 for a while I thought I'd see how people were most often using the type 'dynamic' and why h开发者_StackOverflowas this helped them solve their problem better than they may have done previously?


For example when using reflection.

Example, something like this:

object calc = GetCalculator();
Type calcType = calc.GetType();
object res = calcType.InvokeMember("Add", BindingFlags.InvokeMethod, null, new object[] { 10, 20 });
int sum = Convert.ToInt32(res);

would than become:

dynamic calc = GetCalculator();
int sum = calc.Add(10, 20);

That's a big improvement I think.

But there are more subjects where this can come in handy. For instance when working with COM interop objects this could come in handy, look at: http://www.devx.com/dotnet/Article/42590


It's also used when embedding dynamic languages such as IronPython/IronRuby to allow loading types defined in external source files, and accessing them more directly in C#

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜