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

Sta*_*ver 1 c# c#-4.0

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

private static *bool* Function()
{

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

}
Run Code Online (Sandbox Code Playgroud)

有没有办法做到这一点?在stackoverflow中有一些像这样的问题,但我无法理解.

Dar*_*rov 11

在这种情况下,TryXXX模式似乎是合适的:

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

    return false;
}
Run Code Online (Sandbox Code Playgroud)

然后像这样使用:

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

或者你可以有一个模型:

public class MyModel
{
    public bool Success { get; set; }
    public string Id { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

您的函数可以返回:

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

    return new MyModel
    {
        Success = false,
    };
}
Run Code Online (Sandbox Code Playgroud)

  • +1:只是不要尝试谷歌搜索TryXXX模式;) (6认同)