如何忽略“使用可能未分配的字段‘字段’”?

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

我有以下最小示例代码:

struct MyStruct 
{
    long Size;
}

MyStruct myStruct;
bool result;

if (someCondition)
{
    result = API.SomeThirdPartyCall(out myStruct); // the call will set 'result' to 'true' and assign a value to 'myStruct'
}
if (result)
{
    result = API.AnotherCall(myStruct); //  <-- gives error "Use of possibly unassigned field 'myStruct' (CS0170)"
}

我知道当我尝试使用该结构进行第二次 API 调用时,

myStruct
已被分配了一个值。该API是由第三方提供的,我无法更改它。有什么方法可以忽略我的字段可能未定义的错误吗?

我知道还有一些类似的问题,例如如何检查结构是否已实例化,但解决方案是使用可为空的结构,这对我来说不是一个选择,因为 API 不会接受可为空的结构。

c# struct
1个回答
0
投票

好吧,这可能是一个愚蠢的想法,但因为我假设如果调用没有成功,那么继续该函数/方法是没有用的,你不能

if (SomeCondition)
{
    result = API.SomeThirdPartyCall(out myStruct);
}
else
{
    return;
}

if (result)
{
    result = API.AnotherCall(myStruct);
}
© www.soinside.com 2019 - 2024. All rights reserved.