【问题标题】:How to use generic types in razor page models如何在 Razor 页面模型中使用泛型类型
【发布时间】:2022-01-07 23:10:55
【问题描述】:

我知道this 的问题,但它已经很老了。

我的所有表单都有一个基类。它被称为FormPageModel,它是一个通用基类:


public class FormPageModel<ReadEntity, WriteEntity> where ReadEntity : class, IReadEntity, new(), where WriteEntity : class, IWriteEntity, new()

现在我希望能够使我的FormLayout.cshtml 成为我所有表单的基本布局,强类型。

我试过@model FormPageModel&lt;IReadEntity, IWriteEntity&gt;,但它没有编译。

我有办法在 Razor Pages 中使用泛型作为我的模型吗?

【问题讨论】:

    标签: c# generics razor-pages


    【解决方案1】:

    您无法创建接口的实例,因此IReadEntity 不满足ReadEntity 泛型类型参数上的new() 约束,并且IWriteEntity 不匹配new() 上的约束WriteEntity 泛型类型参数。

    即使你删除了new() 约束,你的类也不能是协变的,所以FormPageModel&lt;SomeReadEntity, SomeWriteEntity&gt; 不能转换为FormPageModel&lt;IReadEntity, IWriteEntity&gt;

    如果您不能使用特定类型,那么您将需要为您的布局模型使用非泛型基类。

    public abstract class FormPageModel 
    {
        ...
    }
    
    public class FormPageModel<ReadEntity, WriteEntity> : FormPageModel
        where ReadEntity : class, IReadEntity, new()
        where WriteEntity : class, IWriteEntity, new()
    {
        ...
    }
    
    @model FormPageModel
    

    【讨论】:

      猜你喜欢
      • 2011-08-09
      • 2021-09-21
      • 2019-02-26
      • 1970-01-01
      • 2017-02-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-09
      相关资源
      最近更新 更多