我正在重构一些代码,并希望在继承链中更高一点的类对它们的参数更严格一点。由于我不确定我是否正确解释了这一点,因此这是我得到的:
public interface ISvdPredictor
{
List<string> Users { get; set; }
List<string> Artists { get; set; }
float PredictRating(ISvdModel model, string user, string artist);
float PredictRating(ISvdModel model, int userIndex, int artistIndex);
}
ISvdPredictor
使用 ISvdModel
:
public interface ISvdModel
{
float[,] UserFeatures { get; set; }
float[,] ArtistFeatures { get; set; }
}
现在我想实现另一个变体:
public interface IBiasSvdPredictor : ISvdPredictor
{
float PredictRating(IBiasSvdModel model, string user, string artist);
float PredictRating(IBiasSvdModel model, int userIndex, int artistIndex);
}
它使用派生自 ISvdModel
的 IBiasSvdModel
:
public interface IBiasSvdModel : ISvdModel
{
float GlobalAverage { get; set; }
float[] UserBias { get; set; }
float[] ArtistBias { get; set; }
}
IBiasSvdPredictor
不适用于 ISvdModel
。
问题是,当我实现 IBiasSvdPredictor
时,我必须实现 2 对 PredictRating 方法。一个来自 ISvdPredictor
,另一个来自 IBiasSvdPredictor
。我需要做什么才能实现来自 IBiasSvdPredictor
的那些?
我也尝试过泛型,但无法使用 where< 将
指令。我可能做错了,所以任何建议都可能有所帮助。我想你明白我想要做什么。BiasSvdPredictor
的 PredictRating
限制为 IBiasSvdModel
/
编辑:如果有人需要更多上下文,请参阅 https://github.com/gligoran/RecommendationSystem .我正在为我的 BSc 论文编写这段代码。
最佳答案
您可以使用泛型和约束。
public interface ISvdModel
{
float[,] UserFeatures { get; set; }
float[,] ArtistFeatures { get; set; }
}
public interface IBiasSvdModel : ISvdModel
{
float GlobalAverage { get; set; }
float[] UserBias { get; set; }
float[] ArtistBias { get; set; }
}
public interface ISvdPredictor<in TSvdModel>
where TSvdModel : ISvdModel // Require that TSvdModel implements ISvdModel
{
List<string> Users { get; set; }
List<string> Artists { get; set; }
float PredictRating(TSvdModel model, string user, string artist);
float PredictRating(TSvdModel model, int userIndex, int artistIndex);
}
// I would actually avoid declaring this interface. Rather, see comment on the class.
public interface IBiasSvdPredictor : ISvdPredictor<IBiasSvdModel> { }
class BiasSvdPredictor : IBiasSvdPredictor // Preferred : ISvdPredictor<IBiasSvdModel>
{
// ...
public float PredictRating(IBiasSvdModel model, string user, string artist) { }
public float PredictRating(IBiasSvdModel model, int userIndex, int artistIndex) { }
}
关于c# - C#中的继承问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7109996/