在我的项目中,我在派生类中有一些函数,除了每个函数中的一个部分不同之外,它们是相同的。
我想把方法拉到基类。
函数如下所示:
func(parameters)
{
//COMMON BITS
if (someVar == "value1") { htmlFilename = line; }
else if (someVar == "value2") { subVideoLink = line; }
else if (someVar == "value3") { linksH2HeadingWritten = true; }
//COMMON BITS
}
不同函数的中心线看起来都像上面但是“someVar”和“variable = line;”中的不同变量有不同的值格式。
这是一般形式:
if (someVar == "CommandName") { variable = line; }
我的想法是发送函数 a Dictionary<string CommandName, ref string> ...但是我似乎无法制作带有引用字符串的字典...
然后我会删除“变量”的 bool 值,方法是将它们替换为值为“true”或“false”的字符串版本。
有更好的方法吗?
请您参考如下方法:
更好的方法是在您在 func 中调用的基类中定义一个 virtual(或 abstract)方法。然后在每个子类中,您可以使用特定指令覆盖该方法,func 将使用子类的行为。
public class MyBase
{
protected virtual void DoCommand() { throw new NotImplementedException(); }
public void Func()
{
...
DoCommand();
...
}
}
public class MySubClass : MyBase
{
protected override void DoCommand()
{
...
}
}
