0

抱歉,问题标题有点尴尬,但我无法弄清楚如何更清楚地描述这种情况。

比方说,我有四个班级:

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 typewhich 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...
    
4

1 回答 1

0

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

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

于 2013-11-11T01:30:25.940 回答