我有一个问题转换类型。我是(后最小的,详细的代码)尝试这样的代码:

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

但“如果”语句转换的城市,但我不断收到:

  

不能隐式转换类型“字符串”到“布尔”


我想要实现:我有一个有搜索文本和搜索位置两个单选按钮(IE City1或位于City2)文本框搜索引擎

当我接收搜索文本和单选按钮它们在一个字符串的形式

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

当我接收城市单选按钮,他们将在“city1”或“城2”。

的格式

什么我需要做的是转换城市单选按钮为一个int,这样我可以在我的搜索数据集中使用它们。我需要转换"city"整数1"city2"整数2

我理解这可能是一个简单的类型转换但是我不能弄清楚。迄今代码if给我误差以上:

int listingsToSearch;
if (thecitytype = "City1")
{
    listingsToSearch = Convert.ToInt32(1);
}
else
{
    listingsToSearch = Convert.ToInt32(2);
}
有帮助吗?

解决方案

C#相等运算==和不=

if (thecitytype == "City1")

其他提示

下面是一些代码,你可以用NUnit的使用演示了另一种方法来计算listingToSearch - 你还会注意到,使用该技术,你就不需要添加提取物的if / else,等你添加更多的城市 - 的下面的测试表明,该代码将只尝试读取整数单选按钮标签“市”后启动。另外,看什么,你可以在你的主代码编写最底部

[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
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top