简体   繁体   English

声明泛型类的变量

[英]Declare variable of a generic class

I have the following abstract class: 我有以下抽象类:

public abstract class ViewModel<TPrimaryModel> : ObservableObject
    where TPrimaryModel : TwoNames, new()
{
    ...
}

In another class I would like to declare a variable where a ViewModel could be saved to: 在另一个类中,我想声明一个变量,在其中可以将ViewModel保存到:

public class MainViewModel
{
    private ViewModel _currentViewModel;
}

This doesn't work as 2 parameters are required (because of the generic). 这是行不通的,因为需要2个参数(由于通用)。 I don't mind which ViewModel is saved to _currentViewModel, as long as the object inherits from the abstract class ViewModel. 我不介意将哪个ViewModel保存到_currentViewModel,只要该对象从抽象类ViewModel继承即可。

This doesn't work as well: 这也不起作用:

public class MainViewModel
{
    #region Members
    private ViewModel<TwoNames> _currentViewModel;
    #endregion
}

Compiler error: 编译器错误:

The type 'typename' must be a non-abstract type with a public parameterless constructor in order to use it as parameter 'parameter' in the generic type or method 'generic'

This is because TwoNames is an abstract class. 这是因为TwoNames是抽象类。 Removing the "new()" constraint isn't a solution for me as I need to instantiate new objects of "TwoNames" in my abstract class (ViewModel). 对于我来说,删除“ new()”约束不是一个解决方案,因为我需要在抽象类(ViewModel)中实例化“ TwoNames”的新对象。 Any other idea? 还有其他想法吗?

You need to create a non-generic base class: 您需要创建一个非通用基类:

public abstract class ViewModel : ObservableObject
{
    ...
}

public abstract class ViewModel<TPrimaryModel> : ViewModel
    where TPrimaryModel : TwoNames, new()
{
    ...
}

And declare _currentViewModel as type ViewModel : 并将_currentViewModel声明为ViewModel类型:

public class MainViewModel
{
    #region Members
    private ViewModel _currentViewModel;
    #endregion
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM