大家好我写了下面的代码,我正在做的是我想使用Switch
案例来存在我的dictionary
,但我收到错误
Can not implicitly convert string to bool
我的代码如下
List<string> lst = new List<string>();
lst.Add("Delete");
lst.Add("Reports");
lst.Add("Customer");
Dictionary<int, string> d = new Dictionary<int, string>();
d.Add(1, "Delete");
d.Add(2, "Reports");
foreach (string i in lst)
{
if (d.ContainsValue(i))
{
switch (d.ContainsValue(i))
{
case "Delete": // Here i would like to compare my value from dictionary
//link1.NavigateUrl = "Reports.aspx";
HyperLink1.NavigateUrl = "Delete.aspx";
break;
}
}
else
{
HyperLink2.Attributes["OnClick"] = "alert('Not a Valid User to Perform this operation'); return false";
}
}
答案 0 :(得分:3)
d.ContainsValue(i)
返回布尔值。当你这样做时:
case "Delete"
您尝试将bool与字符串进行比较,因此失败。你需要这样做:
if (d.ContainsValue(i))
{
switch (i)
{
case "Delete": // Here i would like to compare my value from dictionary
//link1.NavigateUrl = "Reports.aspx";
HyperLink1.NavigateUrl = "Delete.aspx";
break;
}
}
答案 1 :(得分:2)
请尝试以下操作:switch (d[i])
答案 2 :(得分:0)
if
中的switch
会返回一个布尔值,而case
表示它必须是string
switch (d.ContainsValue(i))
{
case "Delete": // Here i would like to compare my value from dictionary
//link1.NavigateUrl = "Reports.aspx";
HyperLink1.NavigateUrl = "Delete.aspx";
break;
}
试试这个
switch (d[i])
{
case "Delete": // Here i would like to compare my value from dictionary
//link1.NavigateUrl = "Reports.aspx";
HyperLink1.NavigateUrl = "Delete.aspx";
break;
}
答案 3 :(得分:0)
你可以做这样的事情,避免一起切换:
var lst = new List<string>();
lst.Add("Delete");
lst.Add("Reports");
lst.Add("Customer");
Dictionary<int, string> d = new Dictionary<int, string>();
d.Add(1, "Delete");
d.Add(2, "Reports");
var hyperlinkMap = new Dictionary<string, string>()
{
{ "Delete", "Delete.aspx"},
{ "Reports", "Reports.aspx"}
};
foreach (var i in lst)
{
if(d.ContainsValue(i))
{
HyperLink1.NavigateUrl = hyperlinkMap[i];
}
else
{
HyperLink2.Attributes["OnClick"] = "alert('Not a Valid User to Perform this operation'); return false";
}
}