【问题标题】:How to convert integer to boolean in C#如何在 C# 中将整数转换为布尔值
【发布时间】:2016-11-28 11:40:14
【问题描述】:

我有一个返回的存储过程:

  • 0 - 表格中没有用户没有应用没有角色
  • 1 - 是的,有您需要的用户、角色、应用程序
  • 2 - 没有该名称的用户 = false
  • 3 - 没有该名称的角色 = false

当我在 C# 中调用存储过程时,我得到:

无法将类型“bool”隐式转换为“int”

public int IsUserInRole(IsUserInRole userInRole)
{
    var model =  _userRepository.CheckIfUserIsInRole(userInRole);
    if (model == 1)
    {
        return true;
    }
    else
    {
        return false;
    }
}

我需要使用它来验证登录用户分配的角色,以便我稍后可以根据UserRole 进行授权。

所以我需要来自 SP 的 true 或 false,这意味着我需要将 Integer 转换为 Boolean

我试过Better way to convert an int to a booleanhttp://www.dotnetperls.com/convert-bool-int,但我没有运气:)。

有什么建议可以解决这个问题吗?

【问题讨论】:

  • 你已经返回bool了,有什么问题吗?将签名更改为:public bool IsUserInRole 并将正文更改为(如果您想要更简洁):return _userRepository.CheckIfUserIsInRole(userInRole) == 1;
  • 你需要public bool IsUserInRole(IsUserInRole userInRole)
  • 存储过程返回字节不是 bool,所以我不能让动作返回 bool
  • @Tozi: 但是这个方法应该返回bool,所以把返回类型从int改为bool。

标签: c# type-conversion typeconverter


【解决方案1】:

这将解决您的错误(返回类型为bool 而不是int)并使您的代码更短:

public bool IsUserInRole(IsUserInRole userInRole)
{
    return _userRepository.CheckIfUserIsInRole(userInRole) == 1;
}

【讨论】:

    【解决方案2】:

    intVal 是一个整数,boolVal 是一个布尔变量,那么你可以这样做:

    boolVal = intVal==1;
    

    查看您的方法,您已将返回值指定为 int 并尝试返回导致指定错误的布尔值。如果您将返回类型更改为bool,那么您的代码将按预期正常工作。在更简化的方式中,您可以修改方法签名,如下所示:

    public bool IsUserInRole(IsUserInRole userInRole)
    {
        return _userRepository.CheckIfUserIsInRole(userInRole)==1;
    }
    

    【讨论】:

    • 谢谢,我认为可以解决问题。我会在测试后几分钟内回信。
    • 我已经测试了这个方法,它可以正常工作。谢谢
    猜你喜欢
    • 1970-01-01
    • 2012-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-03
    • 2018-10-22
    • 1970-01-01
    相关资源
    最近更新 更多