简体   繁体   English

C#中函数的动态返回类型

[英]Dynamic return type of function in c#

I have a function which is like below: 我有一个类似下面的功能:

private static *bool* Function()
{

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

}

are there any way to do this? 有什么办法吗? In stackoverflow there are some questions like this but I couldnt understand. 在stackoverflow中有一些这样的问题,但我听不懂。

Seems like the TryXXX pattern is suitable in this case: 在这种情况下,似乎使用TryXXX模式是合适的:

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;
}

Why would you want to do this in this scenario? 您为什么要在这种情况下执行此操作?

Just return null from the function. 只需从函数返回null。 Check if the function returns null from where you are calling it. 检查函数是否从调用位置返回null。

If your scenario is other than what you have described in your question, then you may want to look at generics. 如果您的情况与问题中所描述的不同,则您可能需要查看泛型。

No. Instead, use an out parameter: 否。请改用out参数:

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

    return false;
}

Call it like this: 这样称呼它:

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

}

Caller just need to check whether the return string is empty or not. 调用方只需要检查返回字符串是否为空。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM