【问题标题】:Generic type (T) with type argument (TT) to have a property of that type argument type具有类型实参 (TT) 的泛型类型 (T) 具有该类型实参类型的属性
【发布时间】: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 typeis 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&lt;T,TT&gt; 实例化为CustomViewModelT
  • 相反,是的。我需要它来为页面定义提供类似的东西:@inherits PageOfType&lt;CustomViewModel&lt;CustomModle&gt;&gt;(能够使用this.Model.Value1)。 (同样,这不是关于 MVC,而是关于 C#)。

标签: c# .net generics inheritance


【解决方案1】:

你必须使用协变接口而不是类:ICustomViewModel&lt;out TModel&gt;

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

【讨论】:

  • 好吧,即使我已经提到“因为我不确定在这种情况下我能否轻松使用接口”(由于我的代码逻辑)(但是如果别无选择),这解决了第二个问题(允许代码编译)。但是主要的问题仍然是关于简化这种复杂的初始化PageOfType&lt;CustomViewModel&lt;CustomModel&gt;, CustomModel&gt;();,因为如果它保持原样,不确定开发过程是否会非常方便(和简单)。
  • 我担心没有更好的方法可以做到这一点。您必须使用协变接口。我不确定你问题的第二部分
  • 至于第二部分,你必须使用这样的定义:class CustomPage&lt;TModel&gt; : PageOfType&lt;ICustomViewModel&lt;TModel&gt;&gt;
  • 感谢您的帮助,但我不是在寻找定义它的方法,而是很容易实例化(而不是在这里重复:new PageOfType&lt;CustomViewModel&lt;CustomModel&gt;, CustomModel&gt;())。因为我的最终 PageOfType 显然必须同时具有:CustomViewModel 和对应属性的 CustomModel 类型。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-04-16
  • 1970-01-01
  • 2015-11-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-04
相关资源
最近更新 更多