“类型安全”是什么意思?


当前回答

类型安全意味着可以分配给程序变量的值集必须符合定义良好且可测试的标准。类型安全变量导致程序更加健壮,因为操作变量的算法可以相信变量只接受定义良好的一组值中的一个。保持这种信任可以确保数据和程序的完整性和质量。

For many variables, the set of values that may be assigned to a variable is defined at the time the program is written. For example, a variable called "colour" may be allowed to take on the values "red", "green", or "blue" and never any other values. For other variables those criteria may change at run-time. For example, a variable called "colour" may only be allowed to take on values in the "name" column of a "Colours" table in a relational database, where "red, "green", and "blue", are three values for "name" in the "Colours" table, but some other part of the computer program may be able to add to that list while the program is running, and the variable can take on the new values after they are added to the Colours table.

Many type-safe languages give the illusion of "type-safety" by insisting on strictly defining types for variables and only allowing a variable to be assigned values of the same "type". There are a couple of problems with this approach. For example, a program may have a variable "yearOfBirth" which is the year a person was born, and it is tempting to type-cast it as a short integer. However, it is not a short integer. This year, it is a number that is less than 2009 and greater than -10000. However, this set grows by 1 every year as the program runs. Making this a "short int" is not adequate. What is needed to make this variable type-safe is a run-time validation function that ensures that the number is always greater than -10000 and less than the next calendar year. There is no compiler that can enforce such criteria because these criteria are always unique characteristics of the problem domain.

Languages that use dynamic typing (or duck-typing, or manifest typing) such as Perl, Python, Ruby, SQLite, and Lua don't have the notion of typed variables. This forces the programmer to write a run-time validation routine for every variable to ensure that it is correct, or endure the consequences of unexplained run-time exceptions. In my experience, programmers in statically typed languages such as C, C++, Java, and C# are often lulled into thinking that statically defined types is all they need to do to get the benefits of type-safety. This is simply not true for many useful computer programs, and it is hard to predict if it is true for any particular computer program.

长和短....您需要类型安全吗?如果是,那么编写运行时函数来确保当变量被赋值时,它符合定义良好的标准。缺点是它使域分析对于大多数计算机程序来说非常困难,因为您必须显式地为每个程序变量定义标准。

其他回答

为了更好地理解,请观看下面的视频,该视频演示了类型安全语言(c#)和非类型安全语言(javascript)的代码。

http://www.youtube.com/watch?v=Rlw_njQhkxw

现在来看长文本。

类型安全意味着防止类型错误。当一种类型的数据类型在不知不觉中被分配给另一种类型时,就会发生类型错误,我们会得到不想要的结果。

例如,JavaScript不是一种类型安全语言。在下面的代码中,“num”是一个数值变量,“str”是字符串。Javascript允许我做“num + str”,现在猜测将它做算术或串联。

现在对于下面的代码,结果是“55”,但重要的一点是,它将执行什么样的操作造成了混乱。

这是因为javascript不是一种类型安全的语言。它允许不受限制地将一种类型的数据设置为另一种类型。

<script>
var num = 5; // numeric
var str = "5"; // string
var z = num + str; // arthimetic or concat ????
alert(z); // displays  “55”
</script>

c#是一种类型安全语言。它不允许将一种数据类型分配给另一种数据类型。下面的代码不允许在不同的数据类型上使用“+”运算符。

类型安全意味着编译器将在编译时验证类型,如果试图将错误的类型赋值给变量,则抛出错误。

一些简单的例子:

// Fails, Trying to put an integer in a string
String one = 1;
// Also fails.
int foo = "bar";

这也适用于方法参数,因为你传递显式类型给它们:

int AddTwoNumbers(int a, int b)
{
    return a + b;
}

如果我试着称之为使用:

int Sum = AddTwoNumbers(5, "5");

编译器会抛出一个错误,因为我传递了一个字符串(“5”),而它期待的是一个整数。

在一个松散类型的语言,如javascript,我可以做以下:

function AddTwoNumbers(a, b)
{
    return a + b;
}

如果我这样调用它:

Sum = AddTwoNumbers(5, "5");

Javascript自动将5转换为字符串,并返回“55”。这是由于javascript使用+符号进行字符串连接。为了使它具有类型意识,你需要做如下的事情:

function AddTwoNumbers(a, b)
{
    return Number(a) + Number(b);
}

或者,可能是:

function AddOnlyTwoNumbers(a, b)
{
    if (isNaN(a) || isNaN(b))
        return false;
    return Number(a) + Number(b);
}

如果我这样调用它:

Sum = AddTwoNumbers(5, " dogs");

Javascript自动将5转换为字符串,并追加它们,以返回“5只狗”。

并不是所有的动态语言都像javascript一样宽容(事实上,动态语言并不意味着松散的类型语言(参见Python)),其中一些语言实际上会在无效的类型转换上给你一个运行时错误。

虽然它很方便,但它会给您带来很多容易被忽略的错误,只有通过测试正在运行的程序才能识别出来。就我个人而言,我更喜欢让编译器告诉我是否犯了这个错误。

现在,回到c#…

c#支持一种叫做协方差的语言特性,这基本上意味着你可以用基类型替换子类型,而不会导致错误,例如:

 public class Foo : Bar
 {
 }

在这里,我创建了一个新类(Foo),它是Bar的子类。我现在可以创建一个方法:

 void DoSomething(Bar myBar)

并使用Foo或Bar作为参数调用它,两者都不会引起错误。这是因为c#知道Bar的任何子类都将实现Bar的接口。

然而,你不能做相反的事情:

void DoSomething(Foo myFoo)

在这种情况下,我不能将Bar传递给这个方法,因为编译器不知道Bar实现了Foo的接口。这是因为子类可以(而且通常会)与父类有很大不同。

当然,现在我已经走得太远了,超出了最初问题的范围,但知道这些都是好事:)

类型安全意味着可以分配给程序变量的值集必须符合定义良好且可测试的标准。类型安全变量导致程序更加健壮,因为操作变量的算法可以相信变量只接受定义良好的一组值中的一个。保持这种信任可以确保数据和程序的完整性和质量。

For many variables, the set of values that may be assigned to a variable is defined at the time the program is written. For example, a variable called "colour" may be allowed to take on the values "red", "green", or "blue" and never any other values. For other variables those criteria may change at run-time. For example, a variable called "colour" may only be allowed to take on values in the "name" column of a "Colours" table in a relational database, where "red, "green", and "blue", are three values for "name" in the "Colours" table, but some other part of the computer program may be able to add to that list while the program is running, and the variable can take on the new values after they are added to the Colours table.

Many type-safe languages give the illusion of "type-safety" by insisting on strictly defining types for variables and only allowing a variable to be assigned values of the same "type". There are a couple of problems with this approach. For example, a program may have a variable "yearOfBirth" which is the year a person was born, and it is tempting to type-cast it as a short integer. However, it is not a short integer. This year, it is a number that is less than 2009 and greater than -10000. However, this set grows by 1 every year as the program runs. Making this a "short int" is not adequate. What is needed to make this variable type-safe is a run-time validation function that ensures that the number is always greater than -10000 and less than the next calendar year. There is no compiler that can enforce such criteria because these criteria are always unique characteristics of the problem domain.

Languages that use dynamic typing (or duck-typing, or manifest typing) such as Perl, Python, Ruby, SQLite, and Lua don't have the notion of typed variables. This forces the programmer to write a run-time validation routine for every variable to ensure that it is correct, or endure the consequences of unexplained run-time exceptions. In my experience, programmers in statically typed languages such as C, C++, Java, and C# are often lulled into thinking that statically defined types is all they need to do to get the benefits of type-safety. This is simply not true for many useful computer programs, and it is hard to predict if it is true for any particular computer program.

长和短....您需要类型安全吗?如果是,那么编写运行时函数来确保当变量被赋值时,它符合定义良好的标准。缺点是它使域分析对于大多数计算机程序来说非常困难,因为您必须显式地为每个程序变量定义标准。

类型安全不应与静态/动态类型或强/弱类型相混淆。

类型安全语言是这样一种语言,在这种语言中,只能对数据执行数据类型所允许的操作。也就是说,如果您的数据是X类型,而X不支持操作y,那么该语言将不允许您执行y(X)。

这个定义没有设置何时检查的规则。它可以在编译时(静态类型)或在运行时(动态类型),通常通过异常进行。它可以两者兼有:一些静态类型语言允许您将数据从一种类型转换为另一种类型,并且必须在运行时检查转换的有效性(假设您试图将对象转换为消费者—编译器无法知道它是否可接受)。

Type-safety does not necessarily mean strongly typed, either - some languages are notoriously weakly typed, but still arguably type safe. Take Javascript, for example: its type system is as weak as they come, but still strictly defined. It allows automatic casting of data (say, strings to ints), but within well defined rules. There is to my knowledge no case where a Javascript program will behave in an undefined fashion, and if you're clever enough (I'm not), you should be able to predict what will happen when reading Javascript code.

类型不安全编程语言的一个例子是C语言:在数组边界之外读取/写入数组值的规范没有定义行为。预测将会发生什么是不可能的。C是一种具有类型系统的语言,但不是类型安全的。

概念:

为了像含义一样非常简单的类型安全,它确保变量的类型应该是安全的

没有错误的数据类型,例如不能保存或初始化字符串类型的整数变量 不可访问超出绑定的索引 只允许特定的内存位置

所以这都是关于变量存储类型的安全性。