Using “partial” on a generic class

亡梦爱人 提交于 2019-12-12 11:35:12

问题


Hey guys,
I'm using a generic class called ViewModelCollection<BaseViewModel> which handles a lists of ViewModels and delivers standard add() and delete() commands.

Now I'm wondering if I can "extend" this class using the partial construct for a certain ViewModel, whose name is, say, CarViewModel.

Is something like this possible?

partial class ViewModelCollection<BaseViewModel>
{
    ... some command and list stuff ...
}

partial class ViewModelCollection<CarViewModel>
{
    ... special commands for car view model
}

回答1:


No, you can't, partial just splits the class definition over multiple files, the definition has to be the same. You need to derive from ViewModelCollection<T>:

public class ViewModelCollection<T> where T: BaseViewModel
{
   //methods
}

public class CarViewModelCollection : ViewModelCollection<CarVieModel>
{
  //specific methods
}



回答2:


partial is used only to split a class across multiple source files. The class definition itself must be the same.




回答3:


Take the partial methods added and create an interface, you can then constrain the generic to use that interface and work off of those methods defined.



来源:https://stackoverflow.com/questions/5690301/using-partial-on-a-generic-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!