我的 MVP 结构存在问题,该结构建立在通用演示者、 View 等之上,我觉得我违反了 DRY,而且我不知道如何解决它。
示例。
public class Presenter<TView, TModel>
where TView : IView
where TModel : Model
{}
到目前为止一切都很好,但我想要这样
public class Presenter<TView, TModel>
where TView : IView
where TModel : Model
{}
public class Model<T>
{
public T Value { get;set; }
}
但这不会编译,因为 Model 的 where 需要通用参数。 修复:
public class Presenter<TView, TModel, TModelType>
where TView : IView
where TModel : Model<TModelType>
{}
在这里我觉得我违反了干燥,举个例子
public class MyPresenter : Presenter<IMyView, MyModel, string>
{}
public class MyModel : Model<string>
{}
我在演示者和模型上两次指定字符串类型感到不舒服, 我只想指定演示者使用 MyModel 作为模型,我不在乎模型的类型(泛型)。一种解决方案是删除模型的通用约束,但随后我无法创建我想要的通用模型类层次结构。
我对整个 MVP/泛型的看法是错误的吗?
最佳答案
在 C++ 中,这个问题可以通过 typedef 来解决——而 C# 中实际上没有 typedef。
public class Model<T>
{
typedef T TModelType; // this doesn't exist in C#
public T Value { get;set; }
}
那么,
public class Presenter<TView, TModel>
where TView : IView
where TModel : Model<TModel::TModelType>
{}
您可以使用类型别名来实现
using NewName = any_type<even_generics<with_generics>>
但它是基于文件的——你不能在类中使用它。
我可能会这样做
- 重命名
Model<T>
至ModelOf<T>
- 为
ModelOf<T>
创建一个模型基类(ModelOf<T> : Model
) - 使用
where TModel : Model
模型本身对于定义不依赖于 TModelType 的接口(interface)方法很有用。
关于c# - MVP、泛型和 DRY,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3591410/