[英]How do I determine the generic type of an implemented interface using reflection?
[英]How can I restrict an Interface to be implemented by only a generic type
我最近去过一次面试,面试官问我这个问题-
如何编写一个接口,以使其限制或强制仅由通用类型实现,或者阻止提供实现?
有人可以用一些代码示例回答这个问题,也可以通过示例代码片段提供对完全相同的问题的任何参考,以供理解。 可能吗? 如果是,那么如何;如果否,为什么?
无法限制谁实现您的界面。
您可以给出的唯一限制是接口是通用的
public interface IInterface<T> { }
您还可以将接口的通用T
限制为某种类型。
public interface IInterface<T> where T : GenericConstraint { }
此GenericConstraint
限制也可以是以下内容:
有关可用约束的更多信息,请参见MS Docs-类型参数约束
正如@Saruman指出的那样,强烈建议阅读:
如果使用特定的类名:
type参数必须是指定的基类或从指定的基类派生。
因此,如果我有以下课程:
public class GenericConstraint { }
public class NewGenericConstraint : GenericConstraint{ }
我可以向IInterface<T> where T : GenericConstraint
同时提供GenericConstraint
和NewGenericConstraint
, IInterface<T> where T : GenericConstraint
因为它们都是GenericConstraint
或从GenericConstraint
派生的。
因此,以下类将有效:
public class Subject : IInterface<GenericConstraint> { }
public class Subject : IInterface<NewGenericConstraint> { }
public class Subject<T> : IInterface<T> where T : GenericConstraint { }
public class Subject<T> : IInterface<T> where T : NewGenericConstraint { }
GenericConstraint
不能是密封类,因为如果GenericConstraint
是密封的,例如:
public sealed class GenericConstraint { }
您将无法从中继承,并且以下内容将无法编译:
public class NewGenericConstraint : GenericConstraint { }
因此,提供约束为密封类的通用参数将毫无意义。 因此,编译器强制您将泛型类型限制为非密封类
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.