【发布时间】:2013-11-22 17:31:35
【问题描述】:
对不起,问题标题有点尴尬,但我不知道如何更清楚地描述这种情况。
假设我有四个班级:
public class CustomModel
{
public string Value1 { get; set; }
}
public class CustomModel2 : CustomModel
{
}
public class CustomViewModel<T> where T : CustomModel
{
}
public class PageOfType<T, TT> where T : CustomViewModel<TT> where TT : CustomModel
{
public TT Model { get; set; }
public T ViewModel { get; set; }
}
所以,这个想法很简单:我希望PageOfType 具有某种类型的属性,即is an argument of type 和is an argument for itself。
所以,实例化看起来像这样(这有点复杂,在开发过程中不会很好地使用):
var p0 = new PageOfType<CustomViewModel<CustomModel>, CustomModel>();
var p1 = new PageOfType<CustomViewModel<CustomModel>, CustomModel2>();
// ^^ this line gives an error as, obviously, CustomViewModel<CustomModel> and CustomViewModel<CustomModel2> are not convertable
p0.Model.Value1 = "some string"; // <- this line is perfectly what I need (it works)
那么,你能给我一些线索吗:
-
我应该如何安排所有的“厨房”来简单地拥有这样的东西(换句话说,更不用说
CustomModel两次在初始化时):var p0 = new PageOfType<CustomViewModel<CustomModel>>(); // or even having new PageOfType<CustomViewModel2>(); // (if CustomViewModel2 is just as: // public class CustomViewModel2 : CustomViewModel<CustomModel> // for instance) -
我该如何处理可转换错误(因为我不确定在这种情况下我能否轻松使用接口(除非我别无选择)):
var p1 = new PageOfType<CustomViewModel<CustomModel>, CustomModel2>(); // ^^ this line gives an error as...
【问题讨论】:
-
我已经编辑了你的标题。请参阅“Should questions include “tags” in their titles?”,其中的共识是“不,他们不应该”。
-
@John Saunders 谢谢,约翰。
-
如果您可以分配初始 ViewModel。考虑使用工厂方法来启动 PageOfType 的新实例,因为方法支持类型推断。这允许构造如下:
PageOfType.Create(customViewModel); -
你是否总是将
PageOfType<T,TT>实例化为CustomViewModel为T? -
相反,是的。我需要它来为页面定义提供类似的东西:
@inherits PageOfType<CustomViewModel<CustomModle>>(能够使用this.Model.Value1)。 (同样,这不是关于 MVC,而是关于 C#)。
标签: c# .net generics inheritance