C#:显式声明&QUOT效益;不安全" /编译器选项 [英] C#: Benefit of explicitly stating "unsafe" / compiler option

查看:128
本文介绍了C#:显式声明&QUOT效益;不安全" /编译器选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我理解指针和罕见的需要在C#代码中使用它们。我的问题是:什么是具有在一个代码块明确说明不安全的理由。另外,为什么一定编译器选项更改为允许不安全代码

I understand pointers and the rare need to use them in C# code. My question is: what is the reasoning behind having to explicitly state "unsafe" in a block of code. Additionally, why must a compiler option be changed to allow "unsafe" code?

底线:什么在CLR(或语言规范)使得它,所以我们不能只使用指针,每当我们想要的(就像C和C ++),而不必键入不安全,改变了编译器选项?

Bottom Line: What in the CLR (or language specs) makes it so we can't just use pointers whenever we want (much like C and C++) without having to type "unsafe" and change the compiler option?

对于澄清:我知道什么是不安全和安全的代码。这只是一个我们为什么必须做的所有额外的工作(好吧,没有那么多额外的)只是为了能够使用这些功能。问题

推荐答案

有与C#的创造者安德斯Hejlsberg为采访时表示,关于这一主题的此处。基本上,正是@Marc Gravell说:类型安全第一,明确宣布不安全。

There's an interview with C# Creator Anders Hejlsberg that touches on the subject here. Basically, exactly what @Marc Gravell said: typesafety first, unsafety by explicit declaration.

因此​​,要回答你的问题:没有在CLR阻止它;它是一种语言的成语设计,让您与类型打交道时使用安全手套工作。如果你想利用手套了,这是你的选择,但你必须做出的主动选择采取手套关闭。

So to answer your question: nothing in the CLR prevents it; it's a language idiom designed to allow you to work with safety gloves when dealing with types. If you want to take the gloves off, it's your choice, but you have to make the active choice to take the gloves off.

编辑:

有关澄清:我知道什么
不安全和安全的代码。这只是美元,我们为什么必须做的所有
额外的工作,B $ BA问题(好吧,没有那么多额外)
只是为了能够使用这些功能。

作为我联系采访中提到的,这是一个明确的设计决定。 C#本质上是Java的的演变和在Java中,你不必在所有的指针。但设计师想允许指针;然而,因为C#通常会引入Java开发人员,他们认为这将是最好的,如果在默认的行为是与Java类似,即没有指针,同时还允许通过显式声明指针的使用。

As mentioned in the interview I linked, it was an explicit design decision. C# is essentially an evolution of Java and in Java, you don't have pointers at all. But the designers wanted to allow pointers; however because C# would typically be bringing in Java developers, they felt it would be best if the default behavior be similar to Java, i.e. no pointers, while still allowing the use of pointers by explicit declaration.

所以额外工作,是刻意的去迫使你想想你做之前,你在做什么。由于是明确的,它迫使你至少要考虑:?我为什么要做这个做我的真的需要一个指针时,引用类型就足够了

So the "extra work" is deliberate to force you to think about what you are doing before you do it. By being explicit, it forces you to at least consider: "Why am I doing this? Do I really need a pointer when a reference type will suffice?"

这篇关于C#:显式声明&QUOT效益;不安全" /编译器选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆