[英]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.