我是以下代码编写的.NET新手,首先需要将关键字转换为大写&之后如果没有ladder.Just检查是否正确。我的代码是
private string toupper(string keyword)
{
newkeyword = keyword.ToUpper();
return newkeyword;
}
private string check(String newkeyword)
{
if (newkeyword == SETTELG || SETTHJORT)
{
Response.Redirect("../SMSFunction/SeenSMS.ascx");
}
else if (newkeyword==SKUTTELG || SKUTTHJORT)
{
Response.Redirect("../SMSFunction/ShotSMS.ascx");
}
else if (newkeyword == RUNDBALL)
{
Response.Redirect("../SMSFunction/RoundballSMS.ascx");
}
}
答案 0 :(得分:2)
StringDictionary
不区分大小写,因此您可以避开上/下 - 所以字段:
readonly StringDictionary redirects = new StringDictionary {
{SETTELG, "../SMSFunction/SeenSMS.ascx"},
{SETTHJORT, "../SMSFunction/SeenSMS.ascx"},
{SKUTTELG, "../SMSFunction/ShotSMS.ascx"},
{SKUTTHJORT, "../SMSFunction/ShotSMS.ascx"},
{RUNDBALL, "../SMSFunction/RoundballSMS.ascx"},
};
然后只是:
var path = redirects[keyword];
if(path != null) Response.Redirect(path);
答案 1 :(得分:1)
private void Check(string keyword)
{
switch(keyword.ToUpper())
{
case "SETTELG ":
case "SETTHJORT":
Response.Redirect("../SMSFunction/SeenSMS.ascx");
break;
/*remaining code*/
}
}
按如下方式进行......
答案 2 :(得分:1)
当涉及到关键字和其他(对于域)众所周知的字符串值时,我更喜欢使用某种解析。在你的特定情况下,我可能会定义一个枚举
public enum Keywords {
SettleLG,
SettHjort,
SkutteLG,
SkuttHjort,
RundBall
}
然后你可以解析关键词
//Note this will (deliberately) throw an exception
//if the string does not match a defined value
//depending on your needs you might want to handle that
var parsedKeyword = (Keywords)Enum.Parse(typeof(Keywords),keyword,true);
有了这个,你就可以写一个开关
private string GetRelativUrlFromKeyword(Keywords parsedKeyword){
switch(parsedKeyword)
case Keywords.SetteLG:
case Keywords.SettHjort:
return "../SMSFunction/SeenSMS.ascx";
case Keywords.SkutteLG:
case Keywords.SkuttHjort:
return "../SMSFunction/ShotSMS.ascx";
case KeyWords.RundBall:
return "../SMSFunction/RoundballSMS.ascx";
default:
throw new InvalidOperationException("Keyword not recognized" + parsedKeyword);
}
将所有调用代码放在一起会看起来像这样
var parsedKeyword = (Keywords)Enum.Parse(typeof(Keywords),keyword);
var relativeUrl = GetRelativUrlFromKeyword(parsedKeyword);
Response.Redirect(relativeUrl,true);
通过将值解析为枚举,您还可以验证值(1),这样可以更轻松地查找与传递错误值的代码的其他部分相关的错误。 如果你想在一组值和另一组值之间有一个硬编码的映射,就像关键字和相对URL之间的情况一样,开关结构可以正常工作。
我已经将映射拆分为一个单独的函数,因为它使代码更易于推断每个函数/方法何时执行一项操作。 交换机中的默认情况将引发异常。这是为了捕获添加新关键字但忘记在交换机中处理它。您可以选择其他默认值。我通常喜欢在默认情况下抛出异常,最后可能是因为我在更改代码的其他部分时忘了做某事。 (2)。我还在你的response.redirect中添加了一个bool(true),它告诉框架你完成了响应,并且它可以将它发送到客户端(这是次要的,但我更喜欢使我的代码显式为当涉及到代码的意图时可能。)
(1)如果你没有得到任何关键字字符串让我知道,我可以展示你如何使用TryParse (2)如果我遗漏了一个可能的案例值,如果我在F#中有一个不完整的模式匹配但我不一定可以进行交换(例如,当使用字符串时不是这样)时,我会真的想要编译器警告。 p>