声明泛型类的变量

mos*_*o87 1 c# generics

我有以下抽象类:

public abstract class ViewModel<TPrimaryModel> : ObservableObject
    where TPrimaryModel : TwoNames, new()
{
    ...
}
Run Code Online (Sandbox Code Playgroud)

在另一个类中,我想声明一个可以将ViewModel保存到的变量:

public class MainViewModel
{
    private ViewModel _currentViewModel;
}
Run Code Online (Sandbox Code Playgroud)

这不起作用,因为需要2个参数(因为通用).我不介意将哪个ViewModel保存到_currentViewModel,只要该对象继承自抽象类ViewModel.

这不起作用:

public class MainViewModel
{
    #region Members
    private ViewModel<TwoNames> _currentViewModel;
    #endregion
}
Run Code Online (Sandbox Code Playgroud)

编译错误:

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'
Run Code Online (Sandbox Code Playgroud)

这是因为TwoNames是一个抽象类.删除"new()"约束对我来说不是一个解决方案,因为我需要在我的抽象类(ViewModel)中实例化"TwoNames"的新对象.还有其他想法吗?

Tho*_*que 5

您需要创建一个非泛型基类:

public abstract class ViewModel : ObservableObject
{
    ...
}

public abstract class ViewModel<TPrimaryModel> : ViewModel
    where TPrimaryModel : TwoNames, new()
{
    ...
}
Run Code Online (Sandbox Code Playgroud)

并声明_currentViewModel为类型ViewModel:

public class MainViewModel
{
    #region Members
    private ViewModel _currentViewModel;
    #endregion
}
Run Code Online (Sandbox Code Playgroud)