我再一次在这里寻求帮助。我正在编写我的第一个“真实”应用程序来练习我学到的东西,而且我不确定我的方法。我会尽力解释它,因为我的英语允许我。
应用程序由基本抽象类和从该基类继承的三个类组成。
abstract class BaseClass
{
// Some stuff...
// This method is used in all classes. It gets whole adb output
// and returns it as a string for future formating
protected string ProcessAdbCommand(string command)
{
try
{
_processInfo.Arguments = command;
Process adbProcess = Process.Start(_processInfo);
adbProcess.WaitForExit();
return adbProcess.StandardOutput.ReadToEnd();
}
catch (Exception e)
{
WriteToLog(e.Message);
return null;
}
}
}
在ProcessAdbCommand返回输出后,我将调用另一个根据需要处理输出的方法。原则总是一样的 - 格式化输出并根据输出做出一些有用的东西。
现在我想说清楚,负责输出处理的方法需要在每个继承的类中。但问题是在非常类中它返回不同的值类型(布尔值,IDevice和字符串列表)
我在这里挣扎。首先,我想让它成为受保护的抽象。想想
abstract class BaseClass
{
// Some stuff...
// Same as above
protected string ProcessAdbCommand(string command)
{
//Same as above
}
//Method which will be implemented in every inherited class differently
protected bool|List<IDevice>|string ProcessAdbOutput(string adbOutput)
{
//Method implementation
return bool|List<IDevice>|string
}
}
但是我发现不可能覆盖返回类型。并且因为方法将始终仅在类内部使用,所以我没有理由使用接口“强制”它。
经过一段时间的游戏,我决定忘记强制在派生类中实现,并根据需要编写它们。但你认为这是“合法”的做法吗?您如何解决“真实世界”应用程序中的问题?有什么我仍然缺少或我的方法是错误的吗?谢谢。
苦苦挣扎的新手。
答案 0 :(得分:1)
一种可能的方法是使抽象基类具有通用性并接受T
参数,该参数也可以是ProcessAdbOutput
方法的输出。然后,您创建方法abstract
以确保任何派生类型必须实现它:
public abstract class BaseClass<T>
{
protected string ProcessAdbCommand(string command)
{
return string.Empty;
}
public abstract T ProcessAdbOutput(string result);
}
public class DerivedClass : BaseClass<IList<IDevice>>
{
public override IList<IDevice> ProcessAdbOutput(string result)
{
return new List<IDevice>();
}
}