c# - 简化 C# 中的循环泛型约束?

标签 c# .net generics

给定以下基类:

public abstract class PurchaseSystemControllerBase<TController, TViewModel> : IInitializable
    where TController : PurchaseSystemControllerBase<TController, TViewModel>
    where TViewModel : PurchaseSystemViewModelBase<TController, TViewModel> {

    protected TViewModel ViewModel { get; private set; }

    ...
}

public abstract class PurchaseSystemViewModelBase<TController, TViewModel> : ViewModelBase
    where TController : PurchaseSystemControllerBase<TController, TViewModel>
    where TViewModel : PurchaseSystemViewModelBase<TController, TViewModel> {

    protected TController Controller { get; private set; }

    ...
}

具体实现如下:

public sealed class PurchaseSystemController : PurchaseSystemControllerBase<PurchaseSystemController, PurchaseSystemViewModel> {
    ...
}

public sealed class PurchaseSystemViewModel : PurchaseSystemViewModelBase<PurchaseSystemController, PurchaseSystemViewModel> {
    ...
}

有没有一种方法可以简化这一点,以便可以进行以下操作?

public sealed class PurchaseSystemController : PurchaseSystemControllerBase<PurchaseSystemViewModel> {
    ...
}

public sealed class PurchaseSystemViewModel : PurchaseSystemViewModelBase<PurchaseSystemController> {
    ...
}

最佳答案

不,不幸的是不是 - 至少,据我所知,不会失去一些类型安全性。 我在 my Protocol Buffers port 中有一个非常相似的设置, 在消息类型和它对应的构建器类型之间。

如果您乐于用一些非泛型基类型声明 ViewModelController 属性,那很好 - 但如果您需要知道这两个属性完全对应的类型,你会留下这样的烂摊子。

(请注意,您可能需要考虑 ViewModel 和 Controller 是否应该彼此了解。)

关于c# - 简化 C# 中的循环泛型约束?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25492753/

相关文章:

generics - 为什么我会收到错误 "Expected type parameter, found integral variable"?

haskell - 如何创建一个包含可变向量的类型?

c# - EPPlus 不支持 ExcelHorizo​​ntalAlignment Center 或 Right

c# - 处理 OracleCommand 参数中的空值

c# - 看到很多 clr!CLRSemaphore::Wait in call stack

javascript - 如何发送正确的模型

c# - Application.DoEvents 内存泄漏?

c# - 使用 LINQ 从两个列表中获取所有可能的连接对

c# - 是否可以通过反射调用私有(private)委托(delegate)?如果是那么如何?如果否,那么原因是什么?

generics - 可以将实现特征的所有类型存储在列表中并遍历该列表吗?