我有一个像这样的模型类:
public class GenericModel<T> where T : BaseTest
{
//Ctor
public List<T> TestList{get;set;}
}
我可以正常使用它,因为我在我的 Controller 和 View 中设置了它。 但是我有一个可以被所有 Controller 使用的局部 View 。
我想知道我是否可以在局部 View 中做这样的事情:
@model GenericModel<T>
没有指定通用类型。我能在这里做什么?使用界面或其他东西?
最佳答案
不可能用T
来定义它,因为它需要一个实际的类型来跟在@model
语句之后。
根据我的经验,在 visual studio 中使用重构,为 GenericModel
提取接口(interface),比如 IGenericModel
,为 BaseTest
提取接口(interface),比如 IBaseTest
,那么你的模型语句就变成了:
@model IGenericModel<IBaseTest>
更新:
澄清一下,要提取的接口(interface)可能类似于(注意 out
的变化,如果你使用它会让你的生活更轻松):
public interface IGenericModel<out T> where T : IBaseTest
{
IEnumerable<T> GetAll(); // just as an example
}
public interface IBaseTest
{
T Property { get; }
}
关于c# - 如何在 View 中设置通用模型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23379200/