为什么要在C#中使用动态类型?要在、类型、动态

2023-09-03 00:29:05 作者:﹏ヽ淡漠记忆、忘记回忆つ

起初我以为是这样的:

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();

看起来可读。 但是,比我读(here)该动态类型还配备了性能上的代价。 我试着阅读所有该链接的其他职位明白,我应该用动态类型,但不能想出连一个很好的理由。如果我只是等待的时候,我会告诉自己 - 这只能与动态类型解决?还是有更好的(实际)的原因使用它? 谢谢你。

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.

您的例子仍然是完全静态类型的,并且没有性能损失。您的code编译成完全一样的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.