问题描述
在C ++中,有很多方法可以编写编译代码,但会产生。在C#中有类似的东西吗?我们可以在编译C#中编写代码,但是有未定义的行为?
In C++ there are a lot of ways that you can write code that compiles, but yields undefined behavior (Wikipedia). Is there something similar in C#? Can we write code in C# that compiles, but has undefined behavior?
推荐答案
正如其他人提到的,不安全块可以产生实现定义的行为;滥用不安全的块允许你改变组成运行时本身的代码的字节,因此所有的注单都关闭。
As others have mentioned, pretty much anything in the "unsafe" block can yield implementation-defined behaviour; abuse of unsafe blocks allows you to change the bytes of code that make up the runtime itself, and therefore all bets are off.
整数除法的角落有一个实现定义的行为。
The corner case of integer division has an implementation-defined behaviour.
抛出异常并且从不捕获它导致实现定义的行为 - 终止进程,启动调试器等。
Throwing an exception and never catching it causes implementation-defined behaviour -- terminate the process, start a debugger, and so on.
在C#中有许多其他情况,我们被迫发出具有实现决定的行为的代码。例如,这种情况:
There are a number of other situations in C# where we are forced to emit code which has implementation-determined behaviour. For example, this situation:
但是,一个安全,性能良好的C#程序具有实现定义的行为的情况应该是非常罕见的。
However, the situations in which a safe, well-behaved C# program has implementation-defined behaviour should be quite rare.
这篇关于代码与未定义的行为在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!