有没有办法确保将c#方法返回的值分配给变量?

时间:2020-05-14 09:59:17

标签: c# compiler-errors return-value

我正在编写调用第三方Web API的代码。 Web响应很重要,因为它包含有关是否插入记录的详细信息。 API返回代表已创建对象的JSON。其他插入内容需要返回的ID,例如地址的ID是插入员工之前所需的外键。如果不保留返回值供以后使用,则可能很难跟踪插入的地址。

是否可以注释或编写方法,以便必须分配返回值?这意味着如果不分配其他变量就无法调用该方法,因此您不会意外丢失响应。

例如

[MustAssignReturnResult]
public string InsertRecord(string json)
{
    return "{json representing result}";
}

我希望编译器在未分配的情况下失败。

//this is ok
string result = InsertRecord(json);

//valid under normal circumstances
InsertRecord(json); //but should give a compiler error because result is not assigned.

1 个答案:

答案 0 :(得分:2)

否,您不能强制分配返回值。

但是,您可以将返回值移动到out参数,这样调用方就必须声明一个变量:

public void InsertRecord(string json, out string result)
{
    result = "{json representing result}";
}

现在,呼叫者必须说:

InsertRecord(json, out var result);

但是,您无法使用丢弃变量_停止调用方来忽略结果:

InsertRecord(json, out var _);