[英]Refactoring Derived Classes' Methods to Common Base Class' Method? (C#)
在我的項目中,我在派生類中有一些函數是相同的,除了每個不同的一個部分。
我想將方法拉到基類。
功能如下所示:
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; }
我的想法是發送函數一個Dictionary<string CommandName, ref string>
...然而,似乎我不能在其中創建一個帶有ref字符串的字典...
然后我會刪除'變量'的布爾情況,方法是將它們替換為值為“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()
{
...
}
}
您應該在基類上創建一個可覆蓋的方法:
abstract func(parameters);
並在派生類上實現它:
class CommandN {
...
func(parameters)
{ htmlfilename = line; }
}
class CommandSubVideoLinkX {
...
func(parameters)
{ subVideoLink = line; }
}
等等。
如果我理解你正在嘗試做什么,你可以減少
if (activeCommand.GetType().Name == "CommandName") { variable = line; }
向下:
if (activeCommand is CommandType ) { /*logic, cast if necessary*/ }
當你有一個帶基類的函數但是為派生類型執行特殊情況時非常有用。 這也可以處理另一種類型派生自CommandType的情況。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.