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#
精彩评论