应该有 none 时转换错误,因为 class 实现了所需的接口

Convert error when there should be none since class implements required interface

我的界面如下:

public interface IPageViewModel<T> where T : class
{
    string ViewName { get; set; }
    T SelectedItem { get; set; }
    List<T> ItemsList { get; set; }
}

然后,我有两个 classes:

internal class TestViewModel : IPageViewModel<INotifyPropertyChanged> //let's skip the fact that T is supposed to be a class while it somehow compiles and works with an interface...

internal class HardwareViewModel : IPageViewModel<Hardware>

其中 Hardware 是:

public class Hardware : NotificationObject

NotificationObject是:

public class NotificationObject : INotifyPropertyChanged

最后,我有一个 class 如下:

internal class NavigationViewModel
{
    public List<IPageViewModel<INotifyPropertyChanged>> PageViewModelsList { get; set; } = new List<IPageViewModel<INotifyPropertyChanged>>();

    public NavigationViewModel()
    {
        PageViewModelsList.Add(new TestViewModel());
        PageViewModelsList.Add(new HardwareViewModel()); //error
    }
}

现在,问题是:虽然构造函数中的第一行编译正常,但第二行抛出错误:cannot convert from ViewModels.HardwareViewModel to Helpers.IPageViewModel<System.Component.INotifyPropertyChanged>
但这没有意义。 Hardware 继承自 NotificationObject,后者实现了 INotifyPropertyChanged,因此 IPageViewModel<Hardware> === IPageViewModel<INotifyPropertyChanged>。谁能解释一下为什么会出错?

多亏了评论,我才意识到导致这些问题的主题是 'variance'。因此,在阅读了一些相关内容后,我决定采用此解决方案:

public interface IPageViewModel
{
    string ViewName { get; set; }
}

但是如果有人想保留这些字段并保持他们的接口协变,它必须看起来像这样:

public interface IPageViewModel<out T> where T : class
{
    string ViewName { get; set; }
    T SelectedItem { get; }
    IEnumerable<T> ItemsList { get; }
}