关于强类型:C#是强类型还是弱类型语言?

Is C# a strongly typed or a weakly typed language?

本问题已经有最佳答案,请猛点这里访问。

有人能解释一下C语言是强型还是弱型?解释原因。

如果我有一个名为concat的函数,它可以接受任何对象,那么这就是弱类型吗?

1
2
3
4
function concat(Object stuff)
{
   //do something here to stuff
}


来自http://ericlippert.com/2012/10/15/is-c-a-strengly-typed-or-a-weak-typed-language/

Is C# a strongly typed or a weakly typed language?

Yes.

That is unhelpful.

I don't doubt it. Interestingly, if you rephrased the question as an
"and" question, the answer would be the same.

What? You mean, is C# a strongly typed and a weakly typed language?

Yes, C# is a strongly typed language and a weakly typed language.

I'm confused.

Me too. Perhaps you should tell me precisely what you mean by
"strongly typed" and"weakly typed".

Um. I don't actually know what I mean by those terms, so perhaps that is the question I should be asking. What does it really mean for
a language to be"weakly typed" or"strongly typed"?

"Weakly typed" means"this language uses a type verification system
that I find distasteful", and"strongly typed" means"this language
uses a type system that I find attractive".


C是强类型。

ECMA-334将C定义为"C"(发音为"C sharp"),它是一种简单、现代、面向对象和类型安全的编程语言。

维基百科定义了类型安全

Type safety is synonymous with one of the many definitions of strong
typing; but type safety and dynamic typing are mutually compatible.

维基百科将强类型定义为

In computer science and computer programming, a type system is said to
feature strong typing when it specifies one or more restrictions on
how operations involving values of different data types can be
intermixed. The opposite of strong typing is weak typing.

也许最好问一下C是否是一种类型安全的语言,因为没有人能就"强"和"弱"类型是否真正意味着编译器将进行类型检查达成一致。

C确实有一些类似于动态语言的构造可用,但值得注意的是,这些构造在编译时仍然是类型安全的。

Beginning in Visual C# 3.0, variables that are declared at method
scope can have an implicit type var. An implicitly typed local
variable is strongly typed just as if you had declared the type
yourself, but the compiler determines the type.

http://msdn.microsoft.com/en-us/library/bb383973.aspx

dynamic关键字的工作原理基本相同,只是它是在运行时而不是编译时进行评估,就像var的情况一样。

Visual C# 2010 introduces a new type, dynamic. The type is a static
type, but an object of type dynamic bypasses static type checking. In
most cases, it functions like it has type object. At compile time, an
element that is typed as dynamic is assumed to support any operation.

http://msdn.microsoft.com/en-us/library/dd264736.aspx


一般情况下:c_以强类型方式使用,意思是:变量声明为特定的Type(字符串、int、用户定义的类型等),以后不能分配不同类型的值。

例如:在C中不能有以下内容:

1
2
int i = 10;
i ="ten";

如下面的注释所示,C可以不同地使用。

使用"强"类型可以让编辑器/编译器提醒您出错,并让编辑器向您提供缩小到您可能需要的范围的建议。


强类型和弱类型的定义有很多种,很多种,到了需要在使用这个术语时定义它的含义的程度。我发现一个有用的定义是"语言是否强迫我为参数之类的东西指定类型?"这将诸如C这样的语言分隔到一边,将JavaScript分隔到另一边,我发现这一区别很有用。

要求某人命名一个类型,而不是依赖"duck-typing"这样的东西,这在静态分析中有好处,但在指定共享公共功能的类型时有缺点。因此,这些语言中的许多都进化出复杂的类型关系规范系统,通常是基于第一类的编程,随后是复杂的模板系统或推理系统,这样程序员就可以说"类型A是类型B的子集"或"类型C是一个元类型,可以应用于满足条件的任何其他类型。ONS D和E"等等。


这是一篇关于这个主题的博客文章,作者是C编译器的主要开发人员之一。

简而言之,这个问题本身是有缺陷的,不能以目前的形式得到合理的回答。


根据msdn,c是一种强类型语言。