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. I would like to constrain T so that it must inherit a certain class that defines 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.
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 .
你想要的是一个通用约束 :
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. You could swap out the interface for a class.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.