在。net中什么是类型安全的?

时间:2022-05-14 14:47:56

What is type-safe?

什么是类型安全?

What does it mean and why is it important?

它是什么意思,为什么重要?

6 个解决方案

#1


69  

If you're asking what the idea of "type-safe" in general means, it's the characteristic of code that allows the developer to be certain that a value or object will exhibit certain properties (i.e., be of a certain type) so that he/she can use it in a specific way without fear of unexpected or undefined behavior.

如果你问“类型安全”的概念一般是什么意思,那么代码的特点就是允许开发人员确定一个值或对象将显示某些属性。这样他/她就可以以一种特定的方式使用它,而不必担心意外或不明确的行为。

For instance, in C#, you could say the ArrayList class is not type-safe because it can store any object, which means you can do something like the following:

例如,在c#中,你可以说ArrayList类不是类型安全的,因为它可以存储任何对象,这意味着你可以做以下事情:

var integers = new ArrayList();
integers.Add(1);
integers.Add(2);
integers.Add("3");

for (int i = 0; i < integers.Count; ++i) {
    int integer = (int)integers[i];
    // do something
}

The above will compile because the value "3", even though it's a string and not an integer, can legally be added to an ArrayList since String derives (like Int32) from Object. However, it will throw an InvalidCastException when you try to set integer to (int)integers[2] because a String cannot be cast to an Int32.

上面的代码将被编译,因为即使值“3”是字符串而不是整数,也可以合法地添加到ArrayList中,因为字符串从对象派生(如Int32)。但是,当您试图将整型设置为(int)integer[2]时,它将抛出InvalidCastException,因为字符串不能被转换为Int32。

On the other hand, the List<T> class is type-safe for exactly the opposite reason--i.e., the above code would not compile if integers were a List<int>. Any value that you the developer access from within a type-safe List<int> you can be certain is an int (or whatever the corresponding T is for any generic List<T>); and you can therefore be sure that you'll be able to perform operations such as casting to int (obviously) or, say, long.

另一方面,List 类是类型安全的,原因恰恰相反——例如。,如果整数为 列表,则上述代码不会编译。开发人员从类型安全列表 中访问的任何值都可以确定为int(或任何通用列表 的对应T);因此,您可以确定您将能够执行诸如转换到int(很明显)或(比方说)long的操作。

#2


13  

C - You declare an int, cast it to char and access memory beyond int's boundary

您声明一个int,将它转换为char并访问超出int边界的内存

int i = 10;
char *s = (char*)i;
print(*(s+10));

C# - Types are safe

类型是安全的

int i = 10;
char *s //This is invalid unless you are using unsafe context. 

Pointers are not directly supported by .NET

.NET并不直接支持指针

#3


9  

Type-safe code accesses only the memory locations it is authorized to access. For example, type-safe code cannot read values from another object's private fields. It accesses types only in well-defined, allowable ways.

类型安全代码只访问授权访问的内存位置。例如,类型安全的代码不能从另一个对象的私有字段中读取值。它只以定义良好、允许的方式访问类型。

During just-in-time (JIT) compilation, an optional verification process examines the metadata and Microsoft intermediate language (MSIL) of a method to be JIT-compiled into native machine code to verify that they are type safe. This process is skipped if the code has permission to bypass verification

在即时编译(JIT)过程中,可选的验证过程检查将JIT编译成本机机器码的方法的元数据和Microsoft中间语言(MSIL),以验证它们是类型安全的。如果代码具有绕过验证的权限,则跳过此过程

Although verification of type safety is not mandatory to run managed code, type safety plays a crucial role in assembly isolation and security enforcement. When code is type safe, the common language runtime can completely isolate assemblies from each other. This isolation helps ensure that assemblies cannot adversely affect each other and it increases application reliability.

虽然对类型安全的验证不是强制运行托管代码的,但是类型安全在程序集隔离和安全执行中扮演着至关重要的角色。当代码是类型安全的时候,公共语言运行时可以完全将程序集相互隔离。这种隔离有助于确保程序集不会对彼此产生不利影响,并提高应用程序的可靠性。

For more refer msdn link

更多的参考msdn链接。

A good article explaining it is here

这是一篇很好的文章

#4


-1  

Type safety in .NET has been introduced to prevent the objects of one type from peeking into the memory assigned for the other object.

. net中引入了类型安全,以防止一种类型的对象窥视为另一种对象分配的内存。

For example and detailed discussion please visit this link

例如,详细的讨论请访问这个链接

#5


-1  

Did you mean type-safe in particular or type-safety in general?

你是说类型安全,特别是还是类型安全?

I disagree with the accepted answer: ArrayList is type-safe ignorant (neither type-safe nor not type-safe): https://*.com/a/17984521/1145224

我不同意公认的答案:ArrayList是类型安全的无知(既不是类型安全也不是类型安全):https://*.com/a/17984521/1145224

Richter - CLR via C#, 4th edition (page 93):

Richter - CLR通过c#,第4版(第93页):

Type-safety is the main feature of CLR. You can always discover object's exact type by calling nonvirtual GetType method of the System.Object.

类型安全是CLR的主要特点。您可以通过调用System.Object的非虚GetType方法来发现对象的确切类型。

For example Hero class can not override GetType method to become a type of SuperHero.

例如英雄类不能超越GetType方法成为一种超级英雄。

This System.Object feature enables CLR to check the possibility of casting objects at runtime. For example:

这个系统。对象特性使CLR能够在运行时检查对象转换的可能性。例如:

internal class Employee { ... }

public sealed class Program 
{

    public static Main() 
    {
        DateTime dt = new DateTime(2016, 1, 1);
        PromoteEmployee(newYears);
    }

    public static PromoteEmployee(Object o)
    {
        Employee e = (Employee)o; //InvalidCastException, runtime error
    }
}

Casting DateTime type to Employee type is an example of a not type-safe attempt to cast.

将DateTime类型转换为Employee类型是不使用类型安全的尝试。

#6


-2  

I don't agree with some answers here. C# has few levels of safety.

我不同意这里的一些答案。c#几乎没有安全级别。

EDIT: Type safety has 2 levels of meaning (if we generally discus about programming languages, as in this thread)

编辑:类型安全有两层含义(如果我们通常讨论编程语言,如本文所述)

One is compile time type-safety, near to refactoring etc, compiler catch typos, misspelled assigning of values to wrong variables (properties), i.e. string to int variable. Typical C# code is type-safe, known way to disable this feature is dynamic keyword, or non generic containers, errors like above are delayed to runtime. Example: non-hacking C/C++ code is (generally) type safe at compile time. I think is possible write (hacking) casting in C# which hide type conflicts.

一种是编译时类型安全,接近重构,编译器捕获错误,错误地将值分配给错误的变量(属性),即字符串到int变量。典型的c#代码是类型安全的,禁用此特性的已知方法是dynamic关键字或非泛型容器,上面的错误被延迟到运行时。示例:非黑客的C/ c++代码(通常)在编译时类型是安全的。我认为c#中的写(黑客)转换可以隐藏类型冲突。

Next level is runtime type-safety, C# is safe in general (without unsafe sections). Even dynamic value are checked on runtime. In contrast: C/C++ isn't type safe at runtime. If compiler accept code, un-logical assigning isn't checked at runtime, providing bizarre / strange / system level or late errors, typical for C language.

下一个级别是运行时类型安全,c#通常是安全的(没有不安全的部分)。甚至在运行时检查动态值。相反,C/ c++在运行时并不是类型安全的。如果编译器接受代码,则在运行时不检查非逻辑赋值,提供奇怪/奇怪/系统级别或延迟错误,这是C语言的典型情况。

Few of answerers in this thread mix other areas where C# is safe (memory safety, range safety, null pointer etc). To be strict, these are different kind of safety.

在这个线程中很少有应答者混合其他c#安全的领域(内存安全、范围安全、空指针等)。严格来说,这些是不同的安全。

Theory: https://en.wikipedia.org/wiki/Type_safety

理论:https://en.wikipedia.org/wiki/Type_safety

#1


69  

If you're asking what the idea of "type-safe" in general means, it's the characteristic of code that allows the developer to be certain that a value or object will exhibit certain properties (i.e., be of a certain type) so that he/she can use it in a specific way without fear of unexpected or undefined behavior.

如果你问“类型安全”的概念一般是什么意思,那么代码的特点就是允许开发人员确定一个值或对象将显示某些属性。这样他/她就可以以一种特定的方式使用它,而不必担心意外或不明确的行为。

For instance, in C#, you could say the ArrayList class is not type-safe because it can store any object, which means you can do something like the following:

例如,在c#中,你可以说ArrayList类不是类型安全的,因为它可以存储任何对象,这意味着你可以做以下事情:

var integers = new ArrayList();
integers.Add(1);
integers.Add(2);
integers.Add("3");

for (int i = 0; i < integers.Count; ++i) {
    int integer = (int)integers[i];
    // do something
}

The above will compile because the value "3", even though it's a string and not an integer, can legally be added to an ArrayList since String derives (like Int32) from Object. However, it will throw an InvalidCastException when you try to set integer to (int)integers[2] because a String cannot be cast to an Int32.

上面的代码将被编译,因为即使值“3”是字符串而不是整数,也可以合法地添加到ArrayList中,因为字符串从对象派生(如Int32)。但是,当您试图将整型设置为(int)integer[2]时,它将抛出InvalidCastException,因为字符串不能被转换为Int32。

On the other hand, the List<T> class is type-safe for exactly the opposite reason--i.e., the above code would not compile if integers were a List<int>. Any value that you the developer access from within a type-safe List<int> you can be certain is an int (or whatever the corresponding T is for any generic List<T>); and you can therefore be sure that you'll be able to perform operations such as casting to int (obviously) or, say, long.

另一方面,List 类是类型安全的,原因恰恰相反——例如。,如果整数为 列表,则上述代码不会编译。开发人员从类型安全列表 中访问的任何值都可以确定为int(或任何通用列表 的对应T);因此,您可以确定您将能够执行诸如转换到int(很明显)或(比方说)long的操作。

#2


13  

C - You declare an int, cast it to char and access memory beyond int's boundary

您声明一个int,将它转换为char并访问超出int边界的内存

int i = 10;
char *s = (char*)i;
print(*(s+10));

C# - Types are safe

类型是安全的

int i = 10;
char *s //This is invalid unless you are using unsafe context. 

Pointers are not directly supported by .NET

.NET并不直接支持指针

#3


9  

Type-safe code accesses only the memory locations it is authorized to access. For example, type-safe code cannot read values from another object's private fields. It accesses types only in well-defined, allowable ways.

类型安全代码只访问授权访问的内存位置。例如,类型安全的代码不能从另一个对象的私有字段中读取值。它只以定义良好、允许的方式访问类型。

During just-in-time (JIT) compilation, an optional verification process examines the metadata and Microsoft intermediate language (MSIL) of a method to be JIT-compiled into native machine code to verify that they are type safe. This process is skipped if the code has permission to bypass verification

在即时编译(JIT)过程中,可选的验证过程检查将JIT编译成本机机器码的方法的元数据和Microsoft中间语言(MSIL),以验证它们是类型安全的。如果代码具有绕过验证的权限,则跳过此过程

Although verification of type safety is not mandatory to run managed code, type safety plays a crucial role in assembly isolation and security enforcement. When code is type safe, the common language runtime can completely isolate assemblies from each other. This isolation helps ensure that assemblies cannot adversely affect each other and it increases application reliability.

虽然对类型安全的验证不是强制运行托管代码的,但是类型安全在程序集隔离和安全执行中扮演着至关重要的角色。当代码是类型安全的时候,公共语言运行时可以完全将程序集相互隔离。这种隔离有助于确保程序集不会对彼此产生不利影响,并提高应用程序的可靠性。

For more refer msdn link

更多的参考msdn链接。

A good article explaining it is here

这是一篇很好的文章

#4


-1  

Type safety in .NET has been introduced to prevent the objects of one type from peeking into the memory assigned for the other object.

. net中引入了类型安全,以防止一种类型的对象窥视为另一种对象分配的内存。

For example and detailed discussion please visit this link

例如,详细的讨论请访问这个链接

#5


-1  

Did you mean type-safe in particular or type-safety in general?

你是说类型安全,特别是还是类型安全?

I disagree with the accepted answer: ArrayList is type-safe ignorant (neither type-safe nor not type-safe): https://*.com/a/17984521/1145224

我不同意公认的答案:ArrayList是类型安全的无知(既不是类型安全也不是类型安全):https://*.com/a/17984521/1145224

Richter - CLR via C#, 4th edition (page 93):

Richter - CLR通过c#,第4版(第93页):

Type-safety is the main feature of CLR. You can always discover object's exact type by calling nonvirtual GetType method of the System.Object.

类型安全是CLR的主要特点。您可以通过调用System.Object的非虚GetType方法来发现对象的确切类型。

For example Hero class can not override GetType method to become a type of SuperHero.

例如英雄类不能超越GetType方法成为一种超级英雄。

This System.Object feature enables CLR to check the possibility of casting objects at runtime. For example:

这个系统。对象特性使CLR能够在运行时检查对象转换的可能性。例如:

internal class Employee { ... }

public sealed class Program 
{

    public static Main() 
    {
        DateTime dt = new DateTime(2016, 1, 1);
        PromoteEmployee(newYears);
    }

    public static PromoteEmployee(Object o)
    {
        Employee e = (Employee)o; //InvalidCastException, runtime error
    }
}

Casting DateTime type to Employee type is an example of a not type-safe attempt to cast.

将DateTime类型转换为Employee类型是不使用类型安全的尝试。

#6


-2  

I don't agree with some answers here. C# has few levels of safety.

我不同意这里的一些答案。c#几乎没有安全级别。

EDIT: Type safety has 2 levels of meaning (if we generally discus about programming languages, as in this thread)

编辑:类型安全有两层含义(如果我们通常讨论编程语言,如本文所述)

One is compile time type-safety, near to refactoring etc, compiler catch typos, misspelled assigning of values to wrong variables (properties), i.e. string to int variable. Typical C# code is type-safe, known way to disable this feature is dynamic keyword, or non generic containers, errors like above are delayed to runtime. Example: non-hacking C/C++ code is (generally) type safe at compile time. I think is possible write (hacking) casting in C# which hide type conflicts.

一种是编译时类型安全,接近重构,编译器捕获错误,错误地将值分配给错误的变量(属性),即字符串到int变量。典型的c#代码是类型安全的,禁用此特性的已知方法是dynamic关键字或非泛型容器,上面的错误被延迟到运行时。示例:非黑客的C/ c++代码(通常)在编译时类型是安全的。我认为c#中的写(黑客)转换可以隐藏类型冲突。

Next level is runtime type-safety, C# is safe in general (without unsafe sections). Even dynamic value are checked on runtime. In contrast: C/C++ isn't type safe at runtime. If compiler accept code, un-logical assigning isn't checked at runtime, providing bizarre / strange / system level or late errors, typical for C language.

下一个级别是运行时类型安全,c#通常是安全的(没有不安全的部分)。甚至在运行时检查动态值。相反,C/ c++在运行时并不是类型安全的。如果编译器接受代码,则在运行时不检查非逻辑赋值,提供奇怪/奇怪/系统级别或延迟错误,这是C语言的典型情况。

Few of answerers in this thread mix other areas where C# is safe (memory safety, range safety, null pointer etc). To be strict, these are different kind of safety.

在这个线程中很少有应答者混合其他c#安全的领域(内存安全、范围安全、空指针等)。严格来说,这些是不同的安全。

Theory: https://en.wikipedia.org/wiki/Type_safety

理论:https://en.wikipedia.org/wiki/Type_safety