C#的C/C++互操作性命名约定

ser*_*0ne 12 c c# c++ pinvoke winapi

考虑以下Win32 API结构:

typedef struct _SECURITY_ATTRIBUTES {
  DWORD  nLength;
  LPVOID lpSecurityDescriptor;
  BOOL   bInheritHandle;
} SECURITY_ATTRIBUTES, *PSECURITY_ATTRIBUTES, *LPSECURITY_ATTRIBUTES;
Run Code Online (Sandbox Code Playgroud)

将此对象移植到C#时,我应该遵循此处使用的名称命名约定,如下所示:

public struct _SECURITY_ATTRIBUTES
{
    public int nLength;
    public unsafe byte* lpSecurityDescriptor;
    public int bInheritHandle;
}
Run Code Online (Sandbox Code Playgroud)

或者我可以全力以赴,并以C#样式编写我的结构,如下所示:

public struct SecurityAttributes
{
    private int length;
    private unsafe byte* securityDescriptor;
    private int bInheritHandle;

    public Int32 Length
    {
        get { return this.length; }
        set { this.length = value; }
    }

    public Byte* SecurityDescriptor
    {
        get { return this.seurityDescriptor; }
        set { this.securityDescriptor = value; }
    }

    public Int32 InheritHandle
    {
        get { return this.bInheritHandle; }
        set { this.bInheritHandle = value; }
    }

    public SecurityAttributes(int length, byte* securityDescriptor, int inheritHandle)
    {
        this.length = length;
        this.securityDescriptor = securityDescriptor;
        this.inheritHandle = inheritHandle;
    }
}
Run Code Online (Sandbox Code Playgroud)

虽然第二种方法看起来更优雅,但我想知道是否建议使用以这种方式编写的结构来调用本机功能,或者在从C/C++移植结构时是否存在任何其他缺陷.

Mer*_*aya 3

我认为这不应该是个人偏好。如果要将代码移植到另一种语言,则应应用要移植到的语言的约定。

我肯定会使用 C# 约定,因为代码将由 C# 开发人员使用,而不是 C/C++ 开发人员,对吗?否则我们仍然会_int32 DWORD在 C# 中使用丑陋的代码。

以下是 C# 约定的一些很好的指南: