[英]“Consolidate” all method calls into one?
假设我有几个类在本质上做同样的事情:处理一个字符串,然后将值插入到相应的表中。 因此,从本质上讲,这是一个SWICH ... CASE语句,如下所示。 所有类之间的唯一相似之处是所有类都有一个“ ProcessString”方法。
现在,我想为所有这些方法调用添加一些错误处理。 我可以尝试...捕获所有调用,但是我想知道是否有一种方法可以合并所有这些调用,以便可以在开关末尾调用一个“ ProcessString”,但这适用于其各自的类(有点像为类名设置变量?)。 这样,我可以将异常处理添加到仅一个调用中,并可能使用反射来获取要调用的类和方法。
switch (strKeyword)
{
case "KPI_teachers":
Teachers.processString(strLine, strKeyword, strProcessDate, strProcessHour);
break;
case "KPI_students":
Students.processString(strLine, strKeyword, strProcessDate, strProcessHour);
break;
case "KPI_classrooms":
Classrooms.processString(strLine, strKeyword, strProcessDate, strProcessHour);
break;
}
任何帮助表示赞赏。 谢谢。
不必为了处理异常而将switch
合并为单个语句,但是无论如何这都是一个好习惯。
首先,从类型系统的角度来看,您需要为支持属性的类型(我假设它们是属性,对吗?)赋予一些共同点。 这意味着他们需要实现相同的接口。 从您的代码推断,该接口可能是
interface IStringProcessor // a bad name, but all of this is rather abstract
{
// Those parameter names are highly suspicious -- is string really the
// correct type for something called "processDate"?
void ProcessString(string line, string keyword,
string processDate, string processHour);
}
因此,如果您具有类型为TeacherType
Teachers
属性,则需要使TeacherType
实现IStringProcessor
。 其他两个也一样。
然后,您想创建一个从字符串映射到IStringProcessor
。 那可能是某种IDictionary
,但是现在让我们保持简单并使其成为一种方法。
private IStringProcessor GetProcessor(string name)
{
switch (name)
{
case "KPI_Teachers": return Teachers;
case "KPI_Students": return Students;
case "KPI_Classrooms": return Classrooms;
default: throw new ArgumentException("blah blah");
}
}
现在,您已经具备了执行单语句的所有机制:
// The bad naming tradition continues here -- lose the "str" prefix.
// If you forget what `keyword` is and try to do something inappropriate with it
// the compiler will be happy to chastise you.
GetProcessor(strKeyword).processString(...);
这可能还很遥远,但是:
try
{
case "KPI_teachers":
Teachers.processString(strLine, strKeyword, strProcessDate, strProcessHour);
break;
case "KPI_students":
Students.processString(strLine, strKeyword, strProcessDate, strProcessHour);
break;
case "KPI_classrooms":
Classrooms.processString(strLine, strKeyword, strProcessDate, strProcessHour);
break;
}
catch (Exception Ex)
{}
Finally {}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.