码迷,mamicode.com
首页 > 其他好文 > 详细

out参数

时间:2020-04-11 23:42:37      阅读:85      评论:0      收藏:0      [点我收藏+]

标签:ram   代码   color   summary   匹配   new   res   code   user   

解决方法如果返回多个值,但可能类型不同的问题。

假设一个将整数字符串转为整数的方法。

代码如下:

var number = int.Parse("2"); // 结果:2
var number2 = int.Parse("Hello"); // 报错,与期望传递的值不匹配:只能传递整数类型的字符串
// 解决
if (int.TryParse("2", out var result))
{
    Console.WriteLine($"result = {result}"); // result  = 2
}
else
{
    // 转换失败,与期望传递的值不匹配
}

再比如以下功能代码:

/// <summary>
/// 获取当前用户id列表并返回总数
/// </summary>
/// <param name="total"></param>
/// <returns></returns>
public List<string> GetUserIds(out int total)
{
    var userIds = new List<string>
    {
        "1",
        "2",
        "3"
    };
    total = 9999;
    return userIds;
}
// 调用
var total = 0;
var userIds = GetUserIds(out total);

out参数

标签:ram   代码   color   summary   匹配   new   res   code   user   

原文地址:https://www.cnblogs.com/vting/p/12682705.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!