如何在C#中使用“where”关键字,具有通用接口和inheritance

我想要实现的是:

  • 声明一个generics类(),
  • 将“T”限制为实现IMySpecialInterface 的类型(其中“X”不是已知类型),
  • 并让该类inheritance自父类。

举个不正确的例子:

public class MyClass : MyParentClass where T : IMySpecialInterface { ... } 

实现此目的的正确语法是什么?

谢谢。

除非在运行时创建了类型,否则不能在不知道类型的情况下使用generics。

你最合适的是:

 public class MyClass : MyParentClass where T: IMySpecialInterface { } 

更新还是可以使用dynamic

 public class MyClass : MyParentClass where T : IMySpecialInterface { ... } 

除非为MyClass提供辅助类型,否则您将需要定义IMySpecialInterface的非generics版本。 整个事情看起来像这样:

 public interface IMySpecialInterface { } public interface IMySpecialInterface : IMySpecialInterface { } public MyClass : MyParentClass where T : IMySpecialInterface { }