gli*_*ran 5 c# inheritance refactoring
我正在重构一些代码,并希望继承链中的类更高一些,对它们的参数要严格一些.由于我不确定我是否正确解释了这一点,这就是我所拥有的:
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);
}
Run Code Online (Sandbox Code Playgroud)
ISvdPredictor用途ISvdModel:
public interface ISvdModel
{
float[,] UserFeatures { get; set; }
float[,] ArtistFeatures { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
现在我想实现另一种变体:
public interface IBiasSvdPredictor : ISvdPredictor
{
float PredictRating(IBiasSvdModel model, string user, string artist);
float PredictRating(IBiasSvdModel model, int userIndex, int artistIndex);
}
Run Code Online (Sandbox Code Playgroud)
哪种用途IBiasSvdModel来自ISvdModel:
public interface IBiasSvdModel : ISvdModel
{
float GlobalAverage { get; set; }
float[] UserBias { get; set; }
float[] ArtistBias { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
IBiasSvdPredictor将无法使用ISvdModel.
问题是,当我实现时,IBiasSvdPredictor我必须实现2对PredictRating方法.一个来自ISvdPredictor另一个IBiasSvdPredictor.我需要做些什么才能实现这些IBiasSvdPredictor?
我试着仿制药为好,但不能限制PredictRating为BiasSvdPredictor以IBiasSvdModel使用where指令.我可能做错了所以任何建议都可能有所帮助.我想你得到了我想做的事.
编辑:如果有人需要更多上下文,请参阅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) { }
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
160 次 |
| 最近记录: |