为什么 C# 是静态类型的?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/859186/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 04:33:08  来源:igfitidea点击:

Why is C# statically typed?

c#static-typing

提问by Moon

I am a PHP web programmer who is trying to learn C#.

我是一名正在尝试学习 C# 的 PHP Web 程序员。

I would like to know why C# requires me to specify the data type when creating a variable.

我想知道为什么 C# 要求我在创建变量时指定数据类型。

Class classInstance = new Class();

Why do we need to know the data type before a class instance?

为什么我们需要在类实例之前知道数据类型?

采纳答案by Joel Coehoorn

As others have said, C# is static/strongly-typed. But I take your question more to be "Why would you wantC# to be static/strongly-typed like this? What advantages does this have over dynamic languages?"

正如其他人所说,C# 是静态/强类型的。但我更多地认为您的问题是“为什么您希望C# 像这样是静态/强类型的?与动态语言相比,它有什么优势?”

With that in mind, there are lots of good reasons:

考虑到这一点,有很多很好的理由:

  • StabilityCertain kinds of errors are now caught automatically by the compiler, before the code ever makes it anywhere close to production.
  • Readability/MaintainabilityYou are now providing more information about how the code is supposed to work to future developers who read it. You add information that a specific variable is intended to hold a certain kind of value, and that helps programmers reason about what the purpose of that variable is.

    This is probably why, for example, Microsoft's style guidelines recommended that VB6 programmers put a type prefix with variable names, but that VB.Net programmers do not.

  • PerformanceThis is the weakest reason, but late-binding/duck typing can be slower. In the end, a variable refers to memory that is structured in some specific way. Without strong types, the program will have to do extra type verification or conversion behind the scenes at runtime as you use memory that is structured one way physically as if it were structured in another way logically.

    I hesitate to include this point, because ultimately you often have to do those conversions in a strongly typed language as well. It's just that the strongly typed language leaves the exact timing and extent of the conversion to the programmer, and does no extra work unless it needs to be done. It also allows the programmer to force a more advantageous data type. But these really are attributes of the programmer, rather than the platform.

    That would itself be a weak reason to omit the point, except that a good dynamic language will often make better choices than the programmer. This means a dynamic language can help many programmers write faster programs. Still, for goodprogrammers, strongly-typed languages have the potentialto be faster.

  • Better Dev ToolsIf your IDE knows what type a variable is expected to be, it can give you additional help about what kinds of things that variable can do. This is much harder for the IDE to do if it has to infer the type for you. And if you get more help with the minutia of an API from the IDE, then you as a developer will be able to get your head around a larger, richer API, and get there faster.
  • 稳定性某些类型的错误现在由编译器自动捕获,在代码接近生产之前。
  • 可读性/可维护性您现在正在向阅读它的未来开发人员提供有关代码应该如何工作的更多信息。您添加特定变量旨在保存某种值的信息,这有助于程序员推理该变量的目的是什么。

    这可能就是为什么,例如,Microsoft 的样式指南建议 VB6 程序员为变量名添加类型前缀,而 VB.Net 程序员则不这样做。

  • 性能这是最弱的原因,但后期绑定/鸭子输入可能会更慢。最后,变量指的是以某种特定方式构建的内存。如果没有强类型,程序将不得不在运行时在幕后进行额外的类型验证或转换,因为您使用的内存是以一种物理方式构造的,就好像它以另一种逻辑方式构造一样。

    我犹豫要不要包含这一点,因为最终您通常还必须在强类型语言中进行这些转换。只是强类型语言将转换的确切时间和范围留给了程序员,除非需要完成,否则不会做任何额外的工作。它还允许程序员强制使用更有利的数据类型。但这些确实是程序员的属性,而不是平台的属性。

    这本身就是忽略这一点的弱理由,除了一个好的动态语言通常会比程序员做出更好的选择。这意味着动态语言可以帮助许多程序员编写更快的程序。尽管如此,对于优秀的程序员来说,强类型语言有可能更快。

  • 更好的开发工具如果您的 IDE 知道一个变量应该是什么类型,它可以为您提供关于该变量可以做什么类型的额外帮助。如果 IDE 必须为您推断类型,这对于 IDE 来说要困难得多。如果您从 IDE 获得有关 API 细节的更多帮助,那么作为开发人员,您将能够了解更大、更丰富的 API,并更快地实现目标。

Or perhaps you were just wondering why you have to specify the class name twice for the same variable on the same line? The answer is two-fold:

或者您可能只是想知道为什么必须在同一行中为同一个变量指定两次类名?答案有两个:

  1. Often you don't. In C# 3.0 and later you can use the varkeyword instead of the type name in many cases. Variables created this way are still statically typed, but the type is now inferredfor you by the compiler.
  2. Thanks to inheritance and interfaces sometimes the type on the left-hand side doesn't match the type on the right hand side.
  1. 通常你不会。在 C# 3.0 及更高版本中,您可以var在许多情况下使用关键字而不是类型名称。以这种方式创建的变量仍然是静态类型的,但现在编译器会为您推断类型。
  2. 由于继承和接口,有时左侧的类型与右侧的类型不匹配。

回答by Nick Allen

Because C# is a strongly typed language

因为 C# 是一种强类型语言

回答by Justin Ethier

C# is a statically-typed, strongly-typedlanguage like C or C++. In these languages all variables must be declared to be of a specific type.

C#是静态类型的强类型,如C或C ++语言。在这些语言中,所有变量都必须声明为特定类型。

回答by Darren Kopp

c# is a strongly-typed language, like c++ or java. Therefore it needs to know the type of the variable. you can fudge it a bit in c# 3.0 via the var keyword. That lets the compiler infer the type.

c# 是一种强类型语言,如 c++ 或 java。因此它需要知道变量的类型。您可以在 c# 3.0 中通过 var 关键字对其进行修改。这让编译器可以推断类型。

回答by JerSchneid

That's the difference between a strongly typed and weakly typed language. C# (and C, C++, Java, most more powerful languages) are strongly typed so you must declare the variable type.

这就是强类型语言和弱类型语言之间的区别。C#(以及 C、C++、Java,最强大的语言)是强类型的,因此您必须声明变量类型。

回答by GWLlosa

You need [class name] in front because there are many situations in which the first [class name] is different from the second, like:

前面需要[类名]是因为很多情况下第一个[类名]和第二个是不一样的,比如:

 IMyCoolInterface obj = new MyInterfaceImplementer();
 MyBaseType obj2 = new MySubTypeOfBaseType();

etc. You can also use the word 'var' if you don't want to specify the type explicitely.

等。如果您不想明确指定类型,也可以使用“var”一词。

回答by JaredPar

It's simply how the language was designed. C# is a C-style language and follows in the pattern of having types on the left.

这就是语言的设计方式。C# 是一种 C 风格的语言,遵循左侧有类型的模式。

In C# 3.0 and up you can kind of get around this in many cases with local type inference.

在 C# 3.0 及更高版本中,您可以在许多情况下通过局部类型推断来解决这个问题。

var variable = new SomeClass();

But at the same time you could also argue that you are still declaring a type on the LHS. Just that you want the compiler to pick it for you.

但与此同时,您也可以争辩说您仍在 LHS 上声明一种类型。只是您希望编译器为您选择它。

EDIT

编辑

Please read this in the context of the users original question

请在用户原始问题的上下文中阅读此内容

why do we need [class name] before a variable name?

为什么在变量名之前需要[类名]?

I wanted to comment on several other answers in this thread. A lot of people are giving "C# is statically type" as an answer. While the statement is true (C# is statically typed), it is almost completely unrelated to the question. Static typing does not necessitate a type name being to the left of the variable name. Sure it can help but that is a language designer choice not a necessary feature of static typed languages.

我想评论这个线程中的其他几个答案。很多人给出“C# 是静态类型”作为答案。虽然该陈述是正确的(C# 是静态类型的),但它几乎与问题完全无关。静态类型不需要在变量名的左边有一个类型名。当然它可以提供帮助,但这是语言设计者的选择,而不是静态类型语言的必要特性。

These is easily provable by considering other statically typed languages such as F#. Types in F# appear on the right of a variable name and very often can be altogether ommitted. There are also several counter examples. PowerShell for instance is extremely dynamic and puts all of its type, if included, on the left.

通过考虑其他静态类型语言(如 F#),这些很容易证明。F# 中的类型出现在变量名的右侧,通常可以完全省略。还有几个反例。例如,PowerShell 是非常动态的,并且将其所有类型(如果包含)放在左侧。

回答by Cuga

When we define variables to hold data we have to specify the type of data that those variables will hold. The compiler then checks that what we are doing with the data makes sense to it, i.e. follows the rules. We can't for example store text in a number - the compiler will not allow it.

当我们定义变量来保存数据时,我们必须指定这些变量将保存的数据类型。然后编译器检查我们对数据所做的事情对它有意义,即遵守规则。例如,我们不能将文本存储在数字中 - 编译器不允许这样做。

int a = "fred"; // Not allowed. Cannot implicitly convert 'string' to 'int' 

The variable a is of type int, and assigning it the value "fred" which is a text string breaks the rules- the compiler is unable to do any kind of conversion of this string.

变量 a 是 int 类型,并为其分配值“fred”,这是一个文本字符串违反了规则——编译器无法对这个字符串进行任何类型的转换。

回答by thecoop

In C# 3.0, you can use the 'var' keyword - this uses static type inference to work out what the type of the variable is at compile time

在 C# 3.0 中,您可以使用“var”关键字 - 这使用静态类型推断来计算编译时变量的类型

var foo = new ClassName();

variable 'foo' will be of type 'ClassName' from then on.

从那时起,变量 'foo' 的类型将是 'ClassName'。

回答by Andrew Hare

One of the main reasons is that you can specify different types as long as the type on the left hand side of the assignment is a parent type of the type on the left (or an interface that is implemented on that type).

主要原因之一是您可以指定不同的类型,只要赋值左侧的类型是左侧类型的父类型(或在该类型上实现的接口)。

For example given the following types:

例如给出以下类型:

class Foo { }
class Bar : Foo { }
interface IBaz { }
class Baz : IBaz { }

C# allows you to do this:

C# 允许你这样做:

Foo f = new Bar();
IBaz b = new Baz();

Yes, in most cases the compiler couldinfer the type of the variable from the assignment (like with the varkeyword) but it doesn't for the reason I have shown above.

是的,在大多数情况下,编译器可以从赋值中推断出变量的类型(就像var关键字一样),但由于我上面展示的原因,它不会。

Edit:As a point of order - while C# isstrongly-typed the important distinction (as far as this discussion is concerned) is that it is in fact also a statically-typedlanguage. In other words the C# compiler does static type checking at compilation time.

编辑:作为一个程序点 - 虽然 C#强类型的,但重要的区别(就本次讨论而言)是它实际上也是一种静态类型的语言。换句话说,C# 编译器在编译时进行静态类型检查。

回答by Rob

C#, as others have pointed out, is a strongly, statically-typed language.

正如其他人指出的那样,C# 是一种强静态类型语言。

By stating up front what the type you're intending to create is, you'll receive compile-time warnings when you try to assign an illegal value. By stating up front what type of parameters you accept in methods, you receive those same compile-time warnings when you accidentally pass nonsense into a method that isn't expecting it. It removes the overhead of some paranoia on your behalf.

通过预先说明您打算创建的类型,当您尝试分配非法值时,您将收到编译时警告。通过预先说明您在方法中接受什么类型的参数,当您不小心将无意义传递给不期望它的方法时,您会收到相同的编译时警告。它代表您消除了一些偏执的开销。

Finally, and rather nicely, C# (and many other languages) doesn't have the same ridiculous, "convert anything to anything, even when it doesn't make sense" mentality that PHP does, which quite frankly can trip you up more times than it helps.

最后,相当不错的是,C#(和许多其他语言)没有 PHP 那样可笑的“将任何东西转换为任何东西,即使它没有意义”的心态,坦率地说,这会让你绊倒更多次比它有帮助。