简体   繁体   English

什么是.net中的类型安全?

[英]What is type-safe in .net?

What is type-safe? 什么是类型安全的?

What does it mean and why is it important? 它意味着什么,为什么重要?

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 (ie, 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 . 以上将编译,因为值“3”,即使它是一个字符串而不是一个整数,可以合法地添加到ArrayList因为StringObject派生(如Int32 )。 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 . 然而,它会抛出一个InvalidCastException ,当您尝试设置integer(int)integers[2]因为String不能转换Int32

On the other hand, the List<T> class is type-safe for exactly the opposite reason--ie, the above code would not compile if integers were a List<int> . 另一方面,由于完全相反的原因, List<T>类型安全的 - 即,如果integersList<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> ); 任何值,可以从一种类型安全内的显影剂访问List<int>你可以肯定int (或任何相应T为任何通用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 . 因此,您可以确定您将能够执行诸如转换为int (显然)或者说long

C - You declare an int, cast it to char and access memory beyond int's boundary C - 您声明一个int,将其强制转换为char并访问超出int边界的内存

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

C# - Types are safe C# - 类型是安全的

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

Pointers are not directly supported by .NET .NET不直接支持指针

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. 在即时(JIT)编译期间,可选的验证过程检查要将JIT编译为本机机器代码的方法的元数据和Microsoft中间语言(MSIL),以验证它们是类型安全的。 This process is skipped if the code has permission to bypass verification 如果代码有权绕过验证,则会跳过此过程

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 这里有一篇很好的文章解释它

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 例如,详细讨论请访问此链接

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://stackoverflow.com/a/17984521/1145224 我不同意接受的答案:ArrayList是类型安全的无知(既不是类型安全也不是类型安全): https//stackoverflow.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. 类型安全是CLR的主要特征。 You can always discover object's exact type by calling nonvirtual GetType method of the System.Object. 您始终可以通过调用System.Object的非虚拟 GetType方法来发现对象的确切类型。

For example Hero class can not override GetType method to become a type of SuperHero. 例如,Hero类不能覆盖GetType方法以成为SuperHero的类型。

This System.Object feature enables CLR to check the possibility of casting objects at runtime. 此System.Object功能使CLR能够检查在运行时转换对象的可能性。 For example: 例如:

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类型是一种非类型安全的转换尝试示例。

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), ie string to int variable. 一个是编译时类型安全 ,接近重构等,编译器捕获拼写错误,错误地将值分配给错误的变量(属性),即字符串到int变量。 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. 典型的C#代码是类型安全的,已知的方法是禁用此功能是dynamic关键字,或非通用容器,上述错误会延迟到运行时。 Example: non-hacking C/C++ code is (generally) type safe at compile time. 示例:非攻击性C / C ++代码(通常)在编译时是类型安全的。 I think is possible write (hacking) casting in C# which hide type conflicts. 我认为可能在C#中编写(黑客)转换隐藏类型冲突。

Next level is runtime type-safety , C# is safe in general (without unsafe sections). 下一级是运行时类型安全 ,C#一般是安全的(没有不安全的部分)。 Even dynamic value are checked on runtime. 甚至动态值也会在运行时检查。 In contrast: C/C++ isn't type safe at runtime. 相反:C / C ++在运行时不是类型安全的。 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语言的典型错误。

Few of answerers in this thread mix other areas where C# is safe (memory safety, range safety, null pointer etc). 这个帖子中很少有人回答C#安全的其他领域(内存安全,范围安全,空指针等)。 To be strict, these are different kind of safety. 严格来说,这些都是不同的安全。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM