如何过滤掉国家代码?
好的,这就是我正在尝试的。
我有一个包含世界上所有国家/地区的下拉列表。 用户选择一个,然后将该值传递给 case 语句, 如果大小写相符,则会发送一封电子邮件。
我只有四种不同的配方,但我可以有多达几十种 与四封电子邮件中的每一封相匹配的国家/地区。例如:
switch (selectedCountry)
{
case "ca":
sendTo = canadaEmail;
break;
case "uk":
case "de":
case "fr"
sendTo = europeanEmail;
break;
case "bb":
sendTo = barbadosEmail;
break;
default:
sendTo = usEmail;
break;
}
我想知道的是,有什么比这样做更好的方法? 一份巨大的案件陈述?
Okay, here's what I'm attempting.
I have a drop down list with all of the countries in the world.
The user selects one, and that value is passed to a case statement,
if it matches the case, an email is sent.
I only have four different recipents, but I can have upwards to dozens
of countries to match with each one of the four emails. For example:
switch (selectedCountry)
{
case "ca":
sendTo = canadaEmail;
break;
case "uk":
case "de":
case "fr"
sendTo = europeanEmail;
break;
case "bb":
sendTo = barbadosEmail;
break;
default:
sendTo = usEmail;
break;
}
What I would like to know is, what's a better way of doing this rather than having
one huge case statement?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您可以使用字典:
然后使用 TryGetValue 获取值当您需要时:
此方法的一个优点是您的字典不必硬编码到您的程序中。它可以很容易地来自配置文件或数据库。
如果您选择数据库路线,您还可以考虑使用 LINQ:
You can use a dictionary instead:
Then use TryGetValue to get the value when you need it:
One advantage of this method is that your dictionary doesn't have to be hard coded into your program. It could just as easily come from a configuration file or a database.
If you choose the database route you could also consider using LINQ:
您无法回避这样一个事实:在某个地方、以某种方式,您必须枚举国家/地区并将它们分配给电子邮件地址。您可以通过多种方式来实现这一点,无论是数据库、外部 XML 文件还是内部 List 对象。
例如:
这允许您定义映射到特定电子邮件地址的国家/地区列表,而无需遍历每个潜在条目,从而节省了复杂的 switch 语句。不过,我可能倾向于从 XML 文件填充列表,而不是对值进行硬编码。
You can't get around the fact that somewhere, somehow, you'll have to enumerate the countries and assign them to an email address. You could do that in any number of ways, be it a database, an external XML file, or an internal List object.
For example:
This saves you the convoluted switch statement by allowing you to define a list of countries mapped to a particular email address, without going through each potential entry. I might be inclined to populate the list from an XML file instead of hardcoding the values, though.
有几个选项可以消除这种情况:
A couple options that would eliminate the cases:
将其外部化(XML、数据库,无论您喜欢什么......)并仅实现一个选择正确状态机的“状态机”。
Externalize it (XML, database, whatever you like...) and only implement a "state machine" which chooses the right one.
是的——如果你在某个地方有一个硬编码列表,请考虑使用自定义类型的集合:
那么你可以这样做:
虽然,我想说这是非常糟糕的设计,我会鼓励你使用 RDBMS某种。
Yes -- if you have a hard coded list somewhere, consider using a collection of a custom type:
Then you could do something like this:
Although, I'd say this is very poor design and I would encourage you to use a rdbms of some sort.