为什么在 C# 中使用动态类型? [英] Why use dynamic typing in c#?

查看:37
本文介绍了为什么在 C# 中使用动态类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一开始我是这么想的:

At first I thought something like:

var aName=getAllSomethings();

非常不可读,所以我会在没有混淆的余地时使用动态类型,例如:

Is very unreadable, and so I'll use dynamic typing just when there's no room for confusion such as:

AClassName aName = new AClassName();

这里,

var aName=new AClassName();

似乎可读.但比我读到的 (此处) 动态类型也会带来性能上的代价.
我尝试阅读该链接中的所有其他帖子,以了解我应该在哪里使用动态类型,但连一个很好的理由都找不到.我应该等待什么时候告诉自己 - 这只能通过动态输入来解决"??或者有更好的(实际的)理由来使用它吗?

谢谢.

seems readable. But than I read (here) that dynamic typing also comes with a price in performance.
I tried reading all the other posts in that link to understand where I should use dynamic typing, but couldn't come up with even one good reason. Should I just wait for when I'll tell myself - "This can only be solved with dynamic typing" ? Or are there better (practical) reasons for using it?

Thanks.

我的错误(-:会尽快结束这个问题.

My mistake (-: will close this question ASAP.

推荐答案

var 不是动态类型.只是aName的类型是由编译器推断出来的.

var isn't dynamic typing. It's just that the type of aName is inferred by the compiler.

您的示例仍然完全是静态类型的,并且没有性能损失.您的代码被编译成与使用显式类型名称完全相同的 IL.

Your example is still entirely statically typed, and has no performance penalty. Your code is compiled into exactly the same IL as it would be with an explicit type name.

现在在 C# 4 中,动态类型确实存在,但它会被写成:

Now in C# 4, dynamic typing does exist, but it would be written as:

dynamic aName = new AClassName();

我个人的看法是,动态类型在 C# 4 中相对很少有用 - 基本上当您处理仅动态已知的数据时,例如反射,或导航 XML.

My personal belief is that dynamic typing will be relatively rarely useful in C# 4 - basically when you're dealing with data which is already only known dynamically, e.g. reflection, or navigating XML.

这篇关于为什么在 C# 中使用动态类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆