私は以下のような機能を持っています:
private static *bool* Function()
{
if(ok)
return UserId; //string
else
return false; //bool
}
これを行う方法はありますか?stackoverflow では、このような質問がいくつかありますが、理解できませんでした。
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,
};
}
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;
}
private static string Function()
{
if(ok)
return UserId; //string
else
return ""; //string
}
呼び出し元は、戻り文字列が空かどうかを確認するだけです。
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.
いいえ。代わりに、次の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
}