代码之家  ›  专栏  ›  技术社区  ›  Jason

if语句出错-无法将类型隐式转换为“bool”

  •  4
  • Jason  · 技术社区  · 16 年前

    转换类型时出现问题。我在尝试类似这样的代码(稍后是最小的、详细的代码):

    string cityType = "City1";
    int listingsToSearch = 42;
    if (cityType = "City1") // <-- error on this line
    {
        listingsToSearch = 1;
    }
    

    但“如果”的说法是要转换城市,但我不断得到:

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


    我想实现的是:我有一个搜索引擎,它有一个搜索文本的文本框和两个搜索位置的单选按钮(即city1或city2)

    当我收到搜索文本和单选按钮时,它们是字符串形式的

    string thesearchtext, thecitytype;
    thesearchtext = HttpContext.Current.Request.QueryString["s"].ToString();
    thecitytype = HttpContext.Current.Request.QueryString["bt"].ToString();
    

    当我收到“城市”单选按钮时,它们的格式将为“city1”或“city2”。

    我需要做的是将城市单选按钮转换为int,以便在搜索数据集中使用它们。我需要转换 "city" 整数 1 "city2" 整数 2 .

    我知道这可能是一个简单的类型转换,但是我无法理解。到目前为止,代码 if 上面给出了错误:

    int listingsToSearch;
    if (thecitytype = "City1")
    {
        listingsToSearch = Convert.ToInt32(1);
    }
    else
    {
        listingsToSearch = Convert.ToInt32(2);
    }
    
    2 回复  |  直到 9 年前
        1
  •  17
  •   Alexei Levenkov    9 年前

    c# equality operator == 而不是 = :

    if (thecitytype == "City1")
    
        2
  •  1
  •   dplante Tschallacka    16 年前

    这里有一些代码可以与nunit一起使用,它演示了另一种计算listingtosearch的技术-您还将注意到,使用此技术,您不需要添加extract if/else等,因为您添加了更多的城市-下面的测试表明,代码将尝试从单选按钮标签中的“city”开始读取整数。另外,请参阅最下面的部分,了解您可以在主代码中编写什么。

    [Test]
    public void testGetCityToSearch()
    {
    
        // if thecitytype = "City1", listingToSearch = 1
        // if thecitytype = "City2", listingToSearch = 2
    
        doParseCity(1, "City1");
        doParseCity(2, "City2");
        doParseCity(20, "City20");        
    }
    
    public void doParseCity(int expected, string input )
    {
        int listingsToSearch;
        string cityNum = input.Substring(4);
        bool parseResult = Int32.TryParse(cityNum, out listingsToSearch);
        Assert.IsTrue(parseResult);
        Assert.AreEqual(expected, listingsToSearch);
    }
    

    在常规代码中,您只需编写:

    string thecitytype20 = "City20";
    string cityNum20 = thecitytype20.Substring(4);
    bool parseResult20 = Int32.TryParse(cityNum20, out listingsToSearch);
    // parseResult20 tells you whether parse succeeded, listingsToSearch will give you 20