简体   繁体   English

定义一个类MyClass <T> 或函数MyFunction <T> (T x)其中T只能通过实现IMyInterface的类型

[英]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.

相关问题 如何为ICollection定义扩展方法 <T> 其中T:IMyInterface,在方法定义中未指定T - How to Define Extension Method for ICollection<T> where T : IMyInterface without Specifying T in the Method Definition 为什么方法不能声明返回类型`List <IMyInterface>`并返回实现它的具体类 - Why can't a method declare return type `List<IMyInterface>` and return a concrete class implementing it 我可以从泛型类型 T 继承泛型 class 吗? 喜欢我的班级<t> : T</t> - Can I inherit a generic class from a generic type T? Like MyClass<T> : T C#:我可以编写公共类MyGenericClass吗 <T> 在哪里T:MyClass并实现一个接口? - C#: Can I code public class MyGenericClass<T> where T:MyClass AND implement an Interface? 如何迭代List <T> 其中T:MyClass - How to iterate List<T> where T: MyClass 保持字典 <Type, MyClass<T> &gt;哪些元素可按类型引用 - Keep a Dictionary<Type, MyClass<T>> where elements are referenceable by type 如何创建一个 List(of T),其中 T 是 (T) 的接口,List 的内容继承了一个实现 T 接口的抽象类 - How can I create a List(of T) where T is an interface of (T) and the contents of the List inherit an Abstract class that implements the interface of T T实现接口的通用方法<T> - Generic method where T implements Interface<T> 公共 T GetMyClass<t> () where T: MyClass, new() { /* 这没有意义吗? */ }</t> - public T GetMyClass<T>() where T : MyClass, new() { /* is this pointless? */ } 投射我的课堂<T>到我的课堂<dynamic> - Cast MyClass<T> to MyClass<dynamic>
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM