c# - C#中的继承问题

标签 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);
}

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);
}

它使用派生自 ISvdModelIBiasSvdModel:

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< 将 BiasSvdPredictorPredictRating 限制为 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/

相关文章:

C++如何使类类型更通用并将其用作一种接口(interface)

"super"关键字的 c++ 仿真

asp.net-mvc - 从 ViewPage 继承

c++ - 从状态图框架中删除依赖项

php - 需要帮助在 PHP 中重构全局变量

python - 长字典属性行的重构

C# 创建对齐网格功能

C# MSScriptControl 将类传递给函数

c# - 为什么这个 webapi2 属性路由不起作用?

c# - 设置类的返回值