开发者

Most common applications of the C# 4.0 dynamic type

开发者 https://www.devze.com 2022-12-30 18:32 出处:网络
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

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

精彩评论

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