[英]Dynamic return type of function in c#
我有一个类似下面的功能:
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,
};
}
不,你不能那样做。
备择方案:
static object Function() {
if(ok)
return UserId; //string
else
return false; //bool
}
要么:
static object Function(out string userId) {
userId = null;
if (ok) {
userId = UserId;
return true;
}
return false;
}
您为什么要在这种情况下执行此操作?
只需从函数返回null。 检查函数是否从调用位置返回null。
如果您的情况与问题中所描述的不同,则您可能需要查看泛型。
否。请改用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
}
private static string Function()
{
if(ok)
return UserId; //string
else
return ""; //string
}
调用方只需要检查返回字符串是否为空。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.