[英]Define a class MyClass<T> or a function MyFunction<T>(T x) where T can only by a type that implements IMyInterface
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. 我想定义一个类MyClass<T>
和一个非常特殊的函数MyFunc<T>
,但是我想强制T
从(以任何方式)继承一个接口或一个类。 Let's call this IMyInterface
. 我们将此称为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. 我对C#的了解允许我执行此操作的唯一方法是定义一个通用类,检查它是否继承(例如,请参阅如何检查类型是子类型还是对象的类型? ),并引发异常。除此以外。
Is there a way to force this at compile-time, rather than runtime? 有没有办法在编译时而不是运行时强制执行此操作?
Generic type constraints: 通用类型约束:
public void MyFunc<T>() where T : IMyInterface {
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.