【发布时间】:2016-03-22 03:51:54
【问题描述】:
我有一个类以类似的方式使用一组属性(为简洁起见,示例中只显示了两个)。 一般行为是在基类中定义的,而具体行为是在特定接口中定义的
问题是:如果我将它们声明为基类,我必须将它们转换为接口才能调用接口方法。现在如果我将它们声明为接口,当我想调用基方法时,我必须将它们转换为基类。
我在这里使用接口时的目标是提高可测试性(稍后使用依赖注入),并培养“对接口编程”的习惯,但我无法决定哪种方式最好,或者即使整个理由是一开始就很好。
public class Conductor
{
// These properties inherit from base class
// and implement one specific interface each:
// declared as interface:
IPlotterHelper _plotter_helper = new PlotterHelper();
// declared as base class:
Helper _file_writer_helper = new FileWriterHelper();
// When using handlers defined in specific interfaces:
// have to cast this:
this.NewFrame += ((IPlotterHelper)_file_writer_helper).ProcessFrame();
// but not this:
this.NewSamples += _plotter_helper.ProcessSamples();
// While when using handlers from the base class
// have to cast this to the base class (since it is an interface):
this.CommandSent += ((Helper)_plotter_helper).RunCommand;
// but not this:
this.CommandSent += _file_writer_helper.RunCommand;
}
internal class FileWriterHelper : Helper, IFileWriterHelper
{
IFileWriterHelper.ProcessFrame()
{
// ...
}
// ...
}
internal class PlotterHelper : Helper, IPlotterHelper
{
IPlotterHelper.ProcessSamples ()
{
///
}
// ...
}
internal class Helper
{
internal void RunCommand()
{
// ...
}
}
【问题讨论】:
-
仅供参考,在命名变量时不要使用下划线,除非在开头(表示它们是字段)。
_plotter_helper错了,应该是_plotterHelper等等。 -
“特定行为在特定接口中定义”是什么意思,因为接口不定义行为?
-
如果您发布的代码能够真正编译,那就太好了。现在是狗的早餐。
-
@Enigmativity 我表达得很糟糕。我想说的是“多态性”,每个接口实现者都会以不同的方式实现给定的方法。
标签: c# inheritance interface casting