在 C# 中拆箱结构上可能为空的值 - 寻找替代解决方案

问题描述 投票:0回答:1

对于以下代码,我在使用 C# Dev Kit 的 VS Code 中收到警告

Unboxing a possibly null value. (CS8605)

Unboxing a possibly null value

带警告的原始代码:

// Originally a struct
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
private struct POLICY_DNS_DOMAIN_INFO {
    public LSA_UNICODE_STRING Name;
    public LSA_UNICODE_STRING DnsDomainName;
    public LSA_UNICODE_STRING DnsForestName;
    public GUID DomainGuid;
    public IntPtr pSID;
}

// Additional code removed for simplicity

resultQueryPolicy = LsaQueryInformationPolicy(policyHandle,
    POLICY_INFORMATION_CLASS.PolicyDnsDomainInformation,
    out IntPtr infoStructure
);

winErrorCode = LsaNtStatusToWinError(resultQueryPolicy);

winErrorCode = LsaNtStatusToWinError(resultQueryPolicy);

if (winErrorCode == 0) {

    POLICY_DNS_DOMAIN_INFO domain = (POLICY_DNS_DOMAIN_INFO)Marshal.PtrToStructure(infoStructure, typeof(POLICY_DNS_DOMAIN_INFO));

// Additional code removed for simplicity
}

当前工作解决方案:

// I changed the struct to a class
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
private class POLICY_DNS_DOMAIN_INFO {
    public LSA_UNICODE_STRING Name;
    public LSA_UNICODE_STRING DnsDomainName;
    public LSA_UNICODE_STRING DnsForestName;
    public GUID DomainGuid;
    public IntPtr pSID;
}

// Additional code removed for simplicity

resultQueryPolicy = LsaQueryInformationPolicy(policyHandle,
    POLICY_INFORMATION_CLASS.PolicyDnsDomainInformation,
    out IntPtr infoStructure
);

winErrorCode = LsaNtStatusToWinError(resultQueryPolicy);

if (winErrorCode == 0) {

    // I applied T?
    POLICY_DNS_DOMAIN_INFO? domain = (POLICY_DNS_DOMAIN_INFO?)Marshal.PtrToStructure(infoStructure, typeof(POLICY_DNS_DOMAIN_INFO));

// Additional code removed for simplicity
}

我正在寻找替代解决方案(希望简单),而无需将

struct
转换为
class
。 这可能吗?

c# .net-core
1个回答
0
投票

Marshal.PtrToStructure
的返回类型是
object?
,因为如果
null
为0,该方法将返回
infoStructure
。如果你确定
infoStructure
永远不会为0,那么你可以告诉编译器返回值获胜使用 null-forgiving 运算符不会
null

POLICY_DNS_DOMAIN_INFO domain = (POLICY_DNS_DOMAIN_INFO)Marshal.PtrToStructure(infoStructure, typeof(POLICY_DNS_DOMAIN_INFO))!;

注意

!
之前的
;

© www.soinside.com 2019 - 2024. All rights reserved.