c#:有什么方法可以同时定义 class 和接口类型的参数?

c#: any way to define an argument with both class and interface type?

我基本上是在尝试为常规参数找到类似通用约束的东西,比如:

public void foo( Bar x) where x : ISomething {//code that calls functionality from both Bar and ISomething. }

然而,在像这样的简单情况下,我可以简单地创建一个 class 来扩展 Bar 并实现 ISomething,使用它作为参数的类型。

当涉及多个接口时,这似乎会崩溃,因为每个相关的接口组合都需要一个中间 class,即使必须在派生 class 中定义实现无论如何。

这只是我必须忍受并处理它的情况之一,还是有一种优雅的方式来完成它。

泛型可以有多个约束,强制调用者实现所有约束。但不需要您指定该类型的外观。例如;

public void foo<T>(T x) where T : ISomething, Bar {}