![](/img/trans.png)
[英]C# How to inherit class from abstract generic class with generic class as type parameter
[英]C#: How to design a generic class so that the type parameter must inherit a certain class?
我写了一个看起来像这样的课:
public class MyClass<T>
{
public void doSomething()
{
T.somethingSpecial;
}
}
此代码无法编译,因为编译器不知道T是什么。 我想约束T,以便它必须继承某个定义somethingSpecial
类。 如果你能告诉我如何通过限制T来做同样的事情以便它必须实现某个界面,那么奖励积分。
public class MyClass<T> where T: IAmSomethingSpecial
它被称为类型参数约束 。
你想要的是一个通用约束 :
public class MyClass<T> where T : SomeParentClass
您需要通用约束 :
public class MyClass<T> where T : ISomeInterface
{
public void doSomething()
{
instanceOfT.somethingSpecial();
}
}
阅读文档。 通用约束。
class MyClass<T> where T : someinterfaceorbaseclassthatTmustinherit
public interface ISomeInterface
{
void DoSomething();
}
public class MyClass<T> where T : ISomeInterface
{
public void doSomething()
{
T.DoSomething();
}
}
where
关键字允许您指定给定泛型类型的约束。 你可以换掉一个类的接口。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.