在项目中允许使用不安全的代码会有什么后果吗?

Are there any consequences to allow unsafe code in the project?

我有一段代码必须 运行 在不安全的上下文中。默认情况下我无法编译它,因为在项目设置中未选中 "Allow unsafe code" 设置。开启这个功能会有什么不好的后果吗?它会影响项目中的其余代码,例如 运行 时的一些额外检查吗?我想知道为什么会有这个设置,是否只是为了警告或防止人们不必要地使用不安全代码?

我的程序并不真正需要不安全上下文,但有一个很小的地方我需要它,我正在犹豫是否为整个项目启用它,我不希望它影响任何东西,除了在非常特殊的情况下 运行ning 的不安全代码段。

总会有后果...但是有一种方法可以通过创建单独的程序集来减少允许不安全代码的影响。通过这种方式,您只需要为新程序集允许不安全代码,而不是为整个项目启用它。

我将 post Jeroen Mostert 的评论,在我看来这是一个很好的答案:

Assemblies containing unsafe code won't load in a partially trusted environment. This used to be a little more relevant in the days where code access security was more important, but even so, there are still scenarios where needing full trust for an assembly is a potential issue. For your average desktop application it doesn't matter. The main problem with unsafe code is the code itself, of course; abandoning the guarantees of verified managed code is enough to justify having to toggle a flag. Sequestering it into a small assembly is an option.