gpt4 book ai didi

c# - c#中函数的动态返回类型

转载 作者:太空宇宙 更新时间:2023-11-03 17:25:13 25 4
gpt4 key购买 nike

我有一个如下所示的函数:

private static *bool* Function()
{

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

}

有什么办法吗?在 stackoverflow 中有一些这样的问题,但我无法理解。

最佳答案

似乎 TryXXX 模式适合这种情况:

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

return false;
}

然后像这样使用:

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

或者你可以有一个模型:

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

你的函数可以返回:

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

return new MyModel
{
Success = false,
};
}

关于c# - c#中函数的动态返回类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18012461/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com