[英]Using a generic base class as a parameter of a method
I have the following classes 我有以下课程
public class A<T>
{
}
public class B<T> : A<T>
{
}
public class C1 : B<string>
{
}
public class C2 : B<int>
{
}
What I would like to to, is have a method which can take any class derived from B<T>
, like C1
or C2
as a parameter. 我想要的是,有一个方法可以采用从
B<T>
派生的任何类,如C1
或C2
作为参数。 But declaring a method as 但是声明一种方法
public void MyMethod(B<T> x)
does not work, it yields the compiler error 不起作用,它会产生编译器错误
Error CS0246: The type or namespace name `T' could not be found.
错误CS0246:找不到类型或命名空间名称“T”。 Are you missing a using directive or an assembly reference?
您是否缺少using指令或程序集引用? (CS0246)
(CS0246)
I am quite stuck here. 我很困在这里。 Creating a non-generic baseclass for
B<T>
won't work, since I wouldn't be able to derive from A<T>
that way. 为
B<T>
创建非泛型基类将不起作用,因为我无法从那个方式派生出A<T>
。 The only (ugly) solution I could think of is to define an empty dummy-interface which is "implemented" by B<T>
. 我能想到的唯一(丑陋)解决方案是定义一个由
B<T>
“实现”的空虚拟接口。 Is there a more elegant way? 有更优雅的方式吗?
Use a generic method: 使用通用方法:
public void MyMethod<T> (B<T> x)
And you can call it like so: 你可以像这样称呼它:
MyMethod(new B<string>());
MyMethod(new C1());
MyMethod(new C2());
Specify T
on the method: 在方法上指定
T
:
public void MyMethod<T>(B<T> x)
or perhaps on the class containing the method: 或者可能在包含该方法的类上:
public class Foo<T>
{
public void MyMethod(B<T> x){}
}
In both cases you'll need the same type constraints (if any) specified on the original class(es) 在这两种情况下,您都需要在原始类上指定相同的类型约束(如果有)
像这样更改方法的签名:
public void MyMethod<T>(B<T> x)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.