根据某些设置调用方法?
我有一些代码如下所示:
if(someCondition)
{
SomeClass1.DoSomething();
SomeClass2.DoSomethingElse();
SomeClass3.DoSomethingElseAgain();
}
if(someOtherCondition)
{
SomeClass4.WhatEver();
}
现在,有时应该调用所有这些方法,有时只调用一些方法。比如有时候我只想调用
SomeClass2.DoSomethingElse();
SomeClass3.DoSomethingElseAgain();
其余的不应该调用。有没有一个好的模式或技巧来实现这一目标?
谢谢 :-)
I have some code which looks like this:
if(someCondition)
{
SomeClass1.DoSomething();
SomeClass2.DoSomethingElse();
SomeClass3.DoSomethingElseAgain();
}
if(someOtherCondition)
{
SomeClass4.WhatEver();
}
Now, sometimes all of those methods should be called, sometimes only some. For example, sometimes I only want to call
SomeClass2.DoSomethingElse();
SomeClass3.DoSomethingElseAgain();
The rest should not be called. Is there a nice pattern or trick to achieve that?
Thanks :-)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
策略模式在这种情况下会很好地工作:http://en.wikipedia.org/wiki/Strategy_pattern
示例:
The Strategy pattern would work nice in this situation: http://en.wikipedia.org/wiki/Strategy_pattern
Example:
您可以创建一个
List
,并针对每个条件(if(someCondition)
部分),将要调用的方法添加到操作列表,然后在最后循环操作并执行每个操作。如果您的方法与
Action
模式不匹配(零个或一个参数,不返回值),您可以创建另一个以相同方式操作的自定义委托。这里有一些伪代码给你:
我知道这似乎是一种更长、更复杂的方式来执行OP帖子中的if/else方法,但在某些情况下,这实际上可能是一个更好的设计(只是不是所有情况)。很难知道什么会有效,因为 OP 太模糊了。
You could create a
List<Action>
, and for each of the conditions (theif(someCondition)
part), add the method(s) you want to call to the Action list, and then at the end loop through the actions and execute each one.If your methods do not match the
Action<T>
pattern (zero or one parameter, does not return a value), you could create another custom delegate that would act in the same way.And here is some pseudocode for you:
I know this seems like a longer, more convoluted way of doing the if/else approach from the OP's post, but in some cases this could actually be a better design (just not all cases). It's hard to know what would work well, since the OP was so vague.
我认为你可以使用 switch case 块,如下所示,
switch (ext.ToLower())
{
案例“.htm”:
案例“.html”:
类型=“文本/HTML”;
休息;
I think you can use switch case block as below,
switch (ext.ToLower())
{
case ".htm":
case ".html":
type = "text/HTML";
break;