为什么我收到此消息:无法将类型'bool'转换为'string'

时间:2009-07-15 05:00:38

标签: c# .net casting compiler-errors

以下是我正在使用的代码段。

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

    }
}

3 个答案:

答案 0 :(得分:18)

由于此行,您的错误正在发生:

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

您将authenticate设置为等于返回布尔值的true / false计算。试试这个。

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”区域中返回布尔值。没有明显的理由将其保持为字符串格式。

答案 1 :(得分: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();
        }

    }
}

答案 2 :(得分:0)

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

我无意间将前一个函数调用中的最后一个参数砍掉了,这应该是一个布尔值,并且没有关闭括号。