【问题标题】:Verify that generic type implements a certain interface验证泛型类型是否实现了某个接口
【发布时间】:2015-05-14 23:49:54
【问题描述】:

我有以下接口:

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

public interface IViewModel : INotifyPropertyChanged
{
}

我想确保泛型TViewModel 始终是实现接口IViewModel 的类。我可以做到以下几点:

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

但是我将无法访问ViewModel 特定类的所有属性和方法。

如何确保TViewModel 始终是实现接口IViewModel 的类?

【问题讨论】:

  • where TViewModel : IViewModel?但这只是基本的generics
  • 我一定错过了那个页面...抱歉这个基本问题。如果您想将其作为答案,我会将其标记为答案。谢谢。
  • 我已经编辑了你的标题。请参阅“Should questions include “tags” in their titles?”,其中的共识是“不,他们不应该”。

标签: c# generics interface


【解决方案1】:

使用where clause 指定泛型类型约束。

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

【讨论】:

    猜你喜欢
    • 2010-11-10
    • 1970-01-01
    • 2012-06-09
    • 2013-08-16
    • 2010-10-04
    • 2018-07-26
    • 2011-02-01
    • 1970-01-01
    相关资源
    最近更新 更多