1

私は以下のような機能を持っています:

private static *bool* Function()
{

if(ok)
return UserId; //string
else
return false; //bool

}

これを行う方法はありますか?stackoverflow では、このような質問がいくつかありますが、理解できませんでした。

4

5 に答える 5

11

Seems like the TryXXX pattern is suitable in this case:

private static bool TryFunction(out string id)
{
    id = null;
    if (ok)
    {
        id = UserId;
        return true;
    }

    return false;
}

and then use like this:

string id;
if (TryFunction(out id))
{
    // use the id here
}
else
{
    // the function didn't return any id
}

Alternatively you could have a model:

public class MyModel
{
    public bool Success { get; set; }
    public string Id { get; set; }
}

that your function could return:

private static MyModel Function()
{
    if (ok)
    {
        return new MyModel
        {
            Success = true,
            Id = UserId,
        };
    }

    return new MyModel
    {
        Success = false,
    };
}
于 2013-08-02T08:46:25.600 に答える
1

No, you can't do that.

Alternatives:

static object Function() {
    if(ok)
         return UserId; //string
    else
         return false; //bool
}

Or:

static object Function(out string userId) {
    userId = null;
    if (ok) {
         userId = UserId;
         return true;
    }
    return false;
}
于 2013-08-02T08:47:49.080 に答える
0
private static string Function()
{

if(ok)
return UserId; //string
else
return ""; //string

}

呼び出し元は、戻り文字列が空かどうかを確認するだけです。

于 2013-08-02T08:53:23.747 に答える
0

Why would you want to do this in this scenario?

Just return null from the function. Check if the function returns null from where you are calling it.

If your scenario is other than what you have described in your question, then you may want to look at generics.

于 2013-08-02T08:47:28.033 に答える
0

いいえ。代わりに、次のoutパラメーターを使用します。

private bool TryGetUserId(out int userId) {
    if (ok) {
        userId = value;
        return true;
    }

    return false;
}

次のように呼び出します。

int userId = 0;

if (TryGetUserId(out userId)) {
    // it worked.. userId contains the value
}
else {
    // it didnt 
}
于 2013-08-02T08:51:27.187 に答える