c# – 打开通用接口类型的开放实现不等于接口类型?
发布时间:2020-12-15 06:51:17 所属栏目:百科 来源:网络整理
导读:这是一个测试,在我看来,应该过去,但不是. [TestMethod]public void can_get_open_generic_interface_off_of_implementor(){ typeof(OpenGenericWithOpenService).GetInterfaces().First() .ShouldEqual(typeof(IGenericService));}public interface IGeneric
这是一个测试,在我看来,应该过去,但不是.
[TestMethod] public void can_get_open_generic_interface_off_of_implementor() { typeof(OpenGenericWithOpenService<>).GetInterfaces().First() .ShouldEqual(typeof(IGenericService<>)); } public interface IGenericService<T> { } public class OpenGenericWithOpenService<T> : IGenericService<T> { } >为什么不通过? 我通常很好奇,但如果您想知道我在做什么,我正在编写一个Structuremap约定,将所有由类实现的接口转发到实现(作为单例). 解决方法
OpenGenericWithOpenService< T>不实现任意的IGenericService<> – 它实现IGenericService< T>与同级T一样.
显示这个的最好方法是稍微改一下: public class OpenGenericWithOpenService<T1,T2> : IGenericService<T1> {} 现在重要的是,当您要求实现的接口时,您可以将其转换为IGenericService< T1>但是(不一致)不是IGenericService< T2>或任何其他实现. 换句话说,这不是完全开放的 – 它被固定在同一类型的参数上. 我从未对泛型术语非常好,但我希望你看到我的意思. IGenericService<>是一种等待给定类型参数的类型;在这种情况下,你有类型参数 – 它只是恰好是另一个类型参数! 这是一个通过测试: [TestMethod] public void can_get_open_generic_interface_off_of_implementor() { Type[] typeParams = typeof(OpenGenericWithOpenService<>).GetGenericArguments(); Type constructed = typeof(IGenericService<>).MakeGenericType(typeParams); typeof(OpenGenericWithOpenService<>).GetInterfaces().First() .ShouldEqual(constructed); } 如果你改变类来实现(例如)IGenericService< int>相反,它会失败. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- Ruby:在代码中使用rand(),但编写测试来验证概率
- Cocos2d-Html5--打怪升级之路
- objective-c – 使有关释放CGMutablePathRef对象的编译器警
- xcode – 与为MacOSX文件“/usr/lib/libSystem.B.dylib”构
- xml – 使用R和Google Map API获取两点之间的距离(纬度,lon
- ORA-12154: TNS: 无法解析指定的连接标识符
- 如何比较两个X509Certificate2 c#
- iWatch报错: Fail to code sign "***" No valid s
- (六) 自己写简单的u-boot
- 语言无关 – 依赖注入最佳实践和反模式