简体   繁体   English

多个类型参数-约束到相同的基类?

[英]Multiple type parameters - constrain to same base class?

Let's say we have this class structure: 假设我们有这样的类结构:

interface A { }
interface A1 : A { }
interface A2 : A { }
class B : A1 { }
class C : A1 { }
class D : A2 { }
class E : A2 { }

And I want to declare a method with this header: 我想用此标头声明一个方法:

public void DoSomething<T, U>()
    where T : A
    where U : A
    <and also where U inherits/implements same parent as T>

It needs to allow DoSomething<B, C>() : 它需要允许DoSomething<B, C>()

  • where T : A is satisfied - B implements A where T : A满足B实现A
  • where U : A is satisfied - C implements A where U : A满足C实现A
  • <and also where U inherits/implements same parent as T> is satisfied because both B and C implement A1 <and also where U inherits/implements same parent as T>因为BC实现了A1
  • DoSomething<D, E>() is also allowed because D and E both implement A2 也允许DoSomething<D, E>()因为DE都实现A2

But it needs to not allow DoSomething<B, D>() : 但是它不需要允许DoSomething<B, D>()

  • where T : A is satisfied - B implements A where T : A满足B实现A
  • where U : A is satisfied - C implements A where U : A满足C实现A
  • <and also where U inherits/implements same thing as T> is not satisfied because B implements A1 but D does not. <and also where U inherits/implements same thing as T> 不能满足,因为B实现了A1而D没有实现。

Is this possible? 这可能吗?

(I think I've butchered the use of the word 'parent' there, but hopefully it's still clear) (我认为我在那儿已在使用“父母”一词,但希望它仍然很清楚)

The only thing you can do is to provide a third generic type parameter that will let you specify which interface both T and U have to implement: 您唯一可以做的就是提供第三个通用类型参数,该参数可让您指定TU必须实现的接口:

public void DoSomething<T, U, V>()
    where T : V
    where U : V
    where V : A

Now you can do DoSomething<D, E, A1>() but not DoSomething<B, D, A1>() . 现在,您可以执行DoSomething<D, E, A1>()但不能执行DoSomething<B, D, A1>()

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

相关问题 将方法类型参数约束为类通用类型的基础 - Constrain method type argument to be base of class generic type 将类型参数约束为基本类型 - Constrain type parameter to a base type 将方法上的泛型类型约束为从抽象泛型基类的任何变体形式派生的任何类 - Constrain generic type on a method to be any class that is derived from any variant form of an abstract generic base class 访问基类中使用的泛型类型参数 - Accessing generic type parameters used in base class 无法将 C# 基类构造函数约束为仅接受使用派生类型作为泛型类型的类型的注入对象 - Cannot constrain C# base class constructor to only accept injected object of a type that uses the derived type as generic type 基类的相同方法的不同返回类型 - Different return type for same method of a base class 更新不同类型但具有相同基类的记录 - Updating records of different type, but with same base class 根据相同的基本类型处理多个集合 - Processing multiple collections based on the same base type 将System.Type列表约束为从基本类型继承的类型 - Constrain a list of System.Type to types that inherit from a base type 在Ninject中注入相同类型的多个参数 - Injection of multiple parameters of the same type in Ninject
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM