[英]C#: How to design a generic class so that the type parameter must inherit a certain class?
I've written a class that looks like this: 我写了一个看起来像这样的课:
public class MyClass<T>
{
public void doSomething()
{
T.somethingSpecial;
}
}
This code doesn't compile because the compiler has no idea what T is. 此代码无法编译,因为编译器不知道T是什么。 I would like to constrain T so that it must inherit a certain class that defines
somethingSpecial
. 我想约束T,以便它必须继承某个定义
somethingSpecial
类。 Bonus points if you can tell me how to do the same thing by contraining T so that it must implement a certain interface. 如果你能告诉我如何通过限制T来做同样的事情以便它必须实现某个界面,那么奖励积分。
public class MyClass<T> where T: IAmSomethingSpecial
它被称为类型参数约束 。
Use the following type parameter constraint in the class declaration: 在类声明中使用以下类型参数约束:
public class MyClass<T> where T : MyBaseClass
You can read more about type parameter contraints for example here at MSDN . 您可以在MSDN上阅读有关类型参数约束的更多信息。
你想要的是一个通用约束 :
public class MyClass<T> where T : SomeParentClass
You need a Generic Constraint : 您需要通用约束 :
public class MyClass<T> where T : ISomeInterface
{
public void doSomething()
{
instanceOfT.somethingSpecial();
}
}
Read the documentation. 阅读文档。 Generic Constraint.
通用约束。
class MyClass<T> where T : someinterfaceorbaseclassthatTmustinherit
public interface ISomeInterface
{
void DoSomething();
}
public class MyClass<T> where T : ISomeInterface
{
public void doSomething()
{
T.DoSomething();
}
}
The where
keyword allows you to specify constraints on the given generic type. where
关键字允许您指定给定泛型类型的约束。 You could swap out the interface for a class. 你可以换掉一个类的接口。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.