gpt4 book ai didi

c# - 为什么类级 "unsafe"修饰符在使用 "partial"时不一致?

转载 作者:太空狗 更新时间:2023-10-29 21:07:46 25 4
gpt4 key购买 nike

我注意到在部分类的类级别使用 unsafe 修饰符时会出现某种行为,我希望得到一些澄清。

我一直在研究一个相当大的包装器,为了理智起见,我使用 partial 修饰符拆分多个文件。包装器大量使用 unsafe 指针,因此我选择简单地在类级别声明它以覆盖其中的所有内容。

public static unsafe partial class Ruby
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static VALUE CLASS_OF(VALUE obj) => ((RBasic*) obj)->klass;
}

在另一个文件中:

public static unsafe partial class Ruby
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void* DATA_PTR(VALUE obj) => ((RData*) obj)->data;
}

每个部分声明都需要 unsafe 修饰符,以便“允许”和编译不安全代码,这是可以理解的,我希望部分类的类声明需要完全匹配。

但是使用这个逻辑,我也可以拥有另一个不是不安全的文件:

[SuppressUnmanagedCodeSecurity]
public static partial class Ruby
{
[DllImport(RUBY_LIBRARY, CallingConvention = CallingConvention.Cdecl)]
public static extern VALUE rb_ivar_get(VALUE obj, ID name);
}

在这里,我没有使用 unsafe 修饰符,这是完全可以接受的(显然这个文件中没有不安全的代码)。

我希望得到有关允许这样做的原因的澄清。每个部分类的类声明不应该完全匹配吗?不允许更改/排除任何其他类修饰符,例如 privatepublicabstract 等,那么为什么可以使用 不安全。在我看来,这种行为似乎不一致。我的猜测是编译器以某种方式在不同的上下文中运行,但这只是我的猜测,希望比我更了解这方面的人能给出一些启示。

最佳答案

您关于需要一致性的修饰符的断言有点不对。例如,这是完全有效的:

public abstract partial class Foo { }

partial class Foo { }

Foo 将代表一个抽象类,因为它的一部分被声明为抽象类。有关部分类的类修饰符的规则可以在规范的第 10.2.2 节中找到。以下是与 unsafe 分部类相关的文本:

When the unsafe modifier is used on a partial type declaration, only that particular part is considered an unsafe context (§18.1).

sealedabstract 应用于分部类时,该类的所有部分都被视为sealedabstract。但是,它不能两者兼而有之。

事实上,可访问性是部分的唯一类修饰符,必须在所有部分之间保持一致,但不需要在所有部分中设置。

When a partial type declaration includes an accessibility specification (the public, protected, internal, and private modifiers) it must agree with all other parts that include an accessibility specification. If no part of a partial type includes an accessibility specification, the type is given the appropriate default accessibility (§3.5.1).

这基本上归结为不允许同时声明 public partial class Barinternal partial class Bar,因为可访问性在各部分之间变得不一致。声明为没有可访问性的其他部分将默认为已声明的可访问性,或规范第 3.5.1 节中概述的规则指定的默认值。

注意:我引用的规范部分来自 Visual Studio 2017 附带的规范版本。

ECMA-334引用资料如下:

23.2:

When the unsafe modifier is used on a partial type declaration (§15.2.7), only that particular part is considered an unsafe context.

15.2.2.1:

When a partial type declaration (§15.2.7) includes an accessibility specification (via the public, protected, internal, and private modifiers), that specification shall agree with all other parts that include an accessibility specification. If no part of a partial type includes an accessibility specification, the type is given the appropriate default accessibility (§8.5.2).

15.2.2.2 和 15.2.2.3 有关于 abstractsealed 修饰符的规则。

关于c# - 为什么类级 "unsafe"修饰符在使用 "partial"时不一致?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51939000/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com