I want to define a class MyClass<T>
and a very particular function MyFunc<T>
, but I want to force T
to inherit from (in any way) an interface or a class. Let's call this IMyInterface
.
The only way my knowledge of C# allows me to do this is to define a generic class, check if it inherits (see How do I check if a type is a subtype OR the type of an object? for example), and throw an exception otherwise.
Is there a way to force this at compile-time, rather than runtime?
Generic type constraints:
public void MyFunc<T>() where T : IMyInterface {
}
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.