具有类型参数(TT)的泛型类型(T),以具有该类型参数类型的属性

时间:2013-11-11 01:24:22

标签: c# .net generics inheritance

对于有点令人尴尬的问题标题感到抱歉,但我无法弄清楚如何更清楚地描述情况。

让我们说,我有四个班级:

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)

那么,你能给我任何线索:

  • 我应该如何安排所有这些&#34;厨房&#34;只是有这样的东西(换句话说,在初始化时不要提及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...
    

1 个答案:

答案 0 :(得分:0)

你必须使用协变接口而不是类ICustomViewModel<out TModel>

http://msdn.microsoft.com/en-us/library/dd799517(v=vs.110).aspx