简体   繁体   English

验证泛型类型实现特定接口

[英]Verify that generic type implements a certain interface

I have the following interfaces: 我有以下界面:

public interface IView<TViewModel>
{
    TViewModel ViewModel { get; set; }
}

public interface IViewModel : INotifyPropertyChanged
{
}

I would like to make sure that the generic TViewModel is always a class that implements interface IViewModel . 我想确保通用TViewModel始终是实现接口IViewModel的类。 I could do the following: 我可以执行以下操作:

public interface IView
{
    IViewModel ViewModel { get; set; }
}

But then I would not have access to all the properties and methods of the specific class of ViewModel . 但是,那时我将无法访问ViewModel特定类的所有属性和方法。

How can I make sure that TViewModel is always a class that implements interface IViewModel ? 如何确保TViewModel始终是实现接口IViewModel的类?

Specify a generic type constraint using the where clause . 使用where子句指定通用类型约束。

public interface IView<TViewModel> where TViewModel : IViewModel
{
    TViewModel ViewModel { get; set; }
}

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

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