补偿异步方法中缺少'out'参数.

Dar*_*jan 10 .net c# windows-store-apps

我有一个类来处理我正在处理的应用程序中的所有API事务.其方法的一般大纲如下所示:

public static async Task<bool> APICall(int bla)
        {
            HttpResponseMessage response;
            bool res;

            // Post/GetAsync to server depending on call + other logic
            return res;
        }
Run Code Online (Sandbox Code Playgroud)

我想要做的是能够将response.StatusCode返回给调用者,但由于我们不允许使用异步方法使用'out'参数,因此它会使事情变得复杂.

我在考虑返回一个包含bool和响应代码的元组,有没有更好的方法呢?

Tho*_*que 11

我在考虑返回一个包含bool和响应代码的元组,有没有更好的方法呢?

您可以创建一个特定的类来保存结果.就个人而言,我并不喜欢元组,因为名字喜欢Item1或者Item2对价值一无所知.

class APICallResult
{
    public bool Success { get; set; }
    public HttpStatusCode StatusCode { get; set; }
}

    public static async Task<APICallResult> APICall(int bla)
    {
        HttpResponseMessage response;
        bool res;

        // Post/GetAsync to server depending on call + other logic
        return new APICallResult { Success = res, StatusCode = response.StatusCode };
    }
Run Code Online (Sandbox Code Playgroud)

  • +1 Tupples并不可怕,但应该在正确的地方使用.而不是例如linq链中的私有类.不作为公共接口的一部分. (4认同)
  • +1.元组太可怕了.它们不会保存返回的信息. (2认同)

xan*_*tos 8

使用a Tuple<x, y>返回多个值.例如,要返回int和字符串:

return Tuple.Create(5, "Hello");
Run Code Online (Sandbox Code Playgroud)

而且类型是 Tuple<int, string>

或者您可以使用数组模拟out/ ref...如果您将方法传递给一个元素的数组,就像传递一个ref或一个out(取决于谁应该填充元素):

MyMethod(new int[1] { 6 });

void MyMethod(int[] fakeArray)
{
    if (fakeArray == null || fakeArray.Length != 1)
    {
        throw new ArgumentException("fakeArray");
    }

    // as a `ref`
    fakeArray[0] = fakeArray[0] + 1;

    // as an `out`
    fakeArray[0] = 10;
}
Run Code Online (Sandbox Code Playgroud)

或使用复杂的对象......

class MyReturn
{
    public string Text { get; set; }
    public int Value { get; set; }
}

MyMethod(new MyReturn());

void MyMethod(MyReturn ret)
{
    ret.Text = "Hello";
    ret.Value = 10;
}
Run Code Online (Sandbox Code Playgroud)

完成...