【问题标题】:Why am I getting this message: Cannot convert type 'bool' to 'string'为什么我会收到此消息:无法将类型“布尔”转换为“字符串”
【发布时间】:2009-07-15 05:00:38
【问题描述】:

下面是我正在使用的代码 sn-p。

using System;
using System.Collections.Generic;
using System.Text;

namespace businessTMS
{
    public class SignIn
    {
        public string authenticate(String UserName, String password)
        {  
            dataTMS.SignIn data = new dataTMS.SignIn();
          string authenticate=(string)data.authenticate(UserName, password);
            return authenticate;
        }

    }
}

【问题讨论】:

  • 这是一个很好的代码 sn-p 你有,但你的问题是什么,到目前为止你尝试了什么?
  • 您的 dataTMS.SignIn 验证方法肯定会返回一个布尔值。您为什么要在 businessTMS 中返回字符串?如果是这样,您试图将什么字符串推回 UI? “登录”与“未登录”?为什么是字符串?而不仅仅是将它作为 boolean (public bool authenticate(...) ?
  • @Simucal:很好的重新标记,我也正要这样做!
  • 虽然是编译器错误,不是异常。

标签: c# .net casting compiler-errors


【解决方案1】:

您的错误是由于这一行而发生的:

string authenticate = (string)data.authenticate(UserName, password);

您将身份验证设置为等于返回布尔值的真/假计算。试试这个吧。

string authenticate = data.authenticate(UserName, password).ToString();

您还可以通过这样做修改代码以仍然返回字符串:

bool authenticate = data.authenticate(UserName, password);
return authenticate.ToString();

首选选项:
此外,我不确定您为什么要返回 true/false (bool) 的字符串表示形式...如果这是我的函数,我可能会返回这个:

return data.authenticate(UserName, password);

我强烈建议您在 PREFERRED OPTION 区域中简单地返回布尔值。没有明显的理由将其保留为字符串格式。

【讨论】:

    【解决方案2】:

    像这样使用 Boolean.ToString 方法(文档可以在 here 找到):

    using System;
    using System.Collections.Generic;
    using System.Text;
    
    namespace businessTMS
    {
        public class SignIn
        {
            public string authenticate(String UserName, String password)
            {  
                dataTMS.SignIn data = new dataTMS.SignIn();
    
                return data.authenticate(UserName, password).ToString();
            }
    
        }
    }
    

    【讨论】:

      【解决方案3】:

      我收到错误消息“无法将类型 'bool' 转换为 'string'”,但我的代码中出现错误的行不是该消息的原因。

      我无意中从前几行函数调用中删除了最后一个参数,这应该是一个布尔值,并且没有关闭括号。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-05-11
        • 2010-10-04
        • 2011-01-22
        • 2010-09-10
        • 2020-07-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多