【发布时间】:2018-09-04 07:24:56
【问题描述】:
我在想什么是处理这种情况的正确方法:我有一个接口 IService,如下所示:
class Configuration
{
public int Min { get; set; }
public int Max { get; set; }
}
interface IService
{
int Calculate(int userId, Configuration configuration)
}
比方说,我有 5 个实现此接口的类,它们运行良好。 有一天我必须实施第 6 项服务,但这一项有点不同。为了完成它的工作,一个新的服务需要这样的配置:
class ExtendedConfiguration : Configuration
{
public string Filter { get; set; }
}
我的新服务可能如下所示:
class NewService : IService
{
public int Calculate(int userId, Configuration configuration)
{
var extendedConfig = configuration as ExtendedConfiguration;
//Calculating and returning result using extendedConfig...
}
}
看起来不错,服务可以。 但是,我不喜欢这样的事实,Calculate 方法签名需要 Configuration 对象,而实际上需要 ExtendedConfiguration - 否则它将无法进行计算(并且会抛出异常)。
有没有更好的方法来编写这段代码?
【问题讨论】:
-
如何使接口通用?然后
IService<TConfig>可以在Calculate 方法中采用TConfig configuration参数。 -
您可以通过在界面中使用泛型来实现这一点。类似于
int Calculate(int userId, T configuration)和T的东西在接口定义级别被限制为Configuration类型。 -
"(并且会抛出异常)。"仅供参考
configuration as ExtendedConfiguration不会引发异常。如果转换失败,它将返回null。你可以检查一下。 -
这个问题的问题是
Is there a better way of writing this code?取决于很多其他因素,你提到工厂而不喜欢泛型。我觉得你已经回答了你自己的问题。我能想到的唯一其他事情是,制作IServiceExtended,并使用组合。但是我不认为它会解决任何问题然后它会产生,这完全取决于你想在兔子洞里走多远 -
配置不应该是服务的属性吗?还是更像参数?如果它可以在服务中,那么您将能够拥有包含具有 int 参数的方法的 IService,以及将提供专用类型的配置的 IService
。然后你的服务必须实现两者(可能是一个通用接口)。这对你有用吗?