不要在顺序结构中声明可见实例字段警告

Do not declare visible instance fields warning in sequential struct

我在 wpf 应用程序中使用一些 DllImports 来捕获屏幕。我正在 user32.dll 中呼叫 GetWindowRect。它需要传递给它的 rect 结构。结构的布局很重要,因为它是本机调用。

我正在试用 VS 2019 预览版 2,它会给我以前从未见过的警告。 rect 中的所有字段都生成相同的警告:

CA1051 Do not declare visible instance fields

在其余代码中,我通过向字段附加 {get;set;} 将字段变成 属性 来解决此问题。我不知道我是否可以在布局很重要的结构中安全地执行此操作。

Rect 也警告我应该覆盖 Equals。

CA1815 Rect should override Equals.

CA1815 Rect should override the equality (==) and inequality (!=) operators.

虽然我从不比较它,但绝对不需要,我只是想修复警告。

public static class NativeMethods
{
    [DllImport("user32.dll")]
    private static extern IntPtr GetForegroundWindow();

    public static IntPtr _GetForegroundWindow()
    {
        return GetForegroundWindow();
    }

    [DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
    private static extern IntPtr GetDesktopWindow();

    public static IntPtr _GetDesktopWindow()
    {
        return GetDesktopWindow();
    }

    //Am unable to get code analysis to shut up about this.
    [DllImport("user32.dll")]
    private static extern int GetWindowRect(IntPtr hWnd, ref Rect rect);

    public static IntPtr _GetWindowRect(IntPtr hWnd, ref Rect rect)
    {
        return (IntPtr)GetWindowRect(hWnd, ref rect);
    }        
}

[StructLayout(LayoutKind.Sequential)]
public struct Rect
{
    public int Left;
    public int Top;
    public int Right;
    public int Bottom;
}    

如何修复这些警告?

您可以像这样在文件中抑制警告:

#pragma warning disable CA1051, CA1815

或在整个项目的 csproj 文件中禁用它

<NoWarn>CA1051, CA1815</NoWarn>

编辑如果你想修复警告而不是抑制它,你应该遵循警告信息。

I never compare it though and definitely don't need to, I just want to fix the warning.

除非您添加消息建议的运算符,否则将出现警告。警告意味着 "it probably works for you now, but not the best practice"。覆盖结构的相等运算符提高了可读性和性能,结构也应该是不可变的,public 字段打破了不可变性并隐藏了潜在的错误。

CA1051: Do not declare visible instance fields 的文档说:

Cause

An externally visible type has an externally visible instance field.

类型和字段的关键点是外部。因此,修复(因为这应该只在您的应用程序内部使用)是使 struct(以及公开它的 class)internal:

[StructLayout(LayoutKind.Sequential)]
internal struct Rect
{
    public int Left;
    public int Top;
    public int Right;
    public int Bottom;
}    

internal static class NativeMethods
{
    // ...
}

请注意,CA1051 警告不是由 C# 编译器生成的,而是由代码分析生成的,因此可以从 CA 规则集中排除或忽略(尽管文档建议 not suppress it)。