C# 泛型类,其方法采用不同的泛型类

C# 泛型类,其方法采用不同的泛型类,c#,generics,C#,Generics,很抱歉问了这么明显的问题 我有一个T类型的“适配器”泛型类,其中T是一个定义的接口。我想在该类中创建一个方法,该方法采用不同类型的泛型适配器 public interface ICommon { } public class TypeOne : ICommon { } public class TypeTwo : ICommon { } public class Adapter<T> where T : ICommon { void TakeAnotherType(Adap

很抱歉问了这么明显的问题

我有一个T类型的“适配器”泛型类,其中T是一个定义的接口。我想在该类中创建一个方法,该方法采用不同类型的泛型适配器

public interface ICommon { }
public class TypeOne : ICommon { }
public class TypeTwo : ICommon { }

public class Adapter<T> where T : ICommon
{
    void TakeAnotherType(Adapter<S> other)
    { }
}
如果我将方法更改为take
Adapter
,则它会抱怨“two”不是
Adapter
void take另一个类型(Adapter other),其中S:ICommon
{ }
由于
Adapter
的泛型类型
T
被约束为
ICommon
,因此也必须以相同的方式约束
S
,因为它被用作
Adapter
的泛型类型,所以它还必须满足
ICommon
约束。

只要更改即可

void TakeAnotherType(Adapter<S> other)
void take其他类型(适配器其他)
进入

void TakeAnotherType(适配器其他),其中S:ICommon

它应该可以工作。

一旦您指定一个类是泛型的(通过将它命名为
Something
),它中的每个方法都隐式地泛型于该类型
T
。要说一个方法在不同类型上是泛型的,您必须在方法名称中指定该事实,方法名称是调用它
SomeMethod
。然后,此方法的主体将可以访问两种类型,
T
(类在其上是泛型的类型)和
U
(方法在其上是泛型的类)

还要注意类型参数的两个常用约定是
T
U
V
等;或
TSomething
TSomethingElse
TEvenMore
。我想我从来没有见过使用
S

void TakeAnotherType<S>(Adapter<S> other) where S:ICommon
{ }
void TakeAnotherType(Adapter<S> other)
void TakeAnotherType<S>(Adapter<S> other) where S : ICommon