在我看来,这是一个应该通过但没有通过的测试。
[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> { }
- 为什么这不通过?
- Given
Type t = typeof(OpenGenericWithOpenService<>)
如何获取 typeof(IGenericService)?
我通常很好奇,但如果您想知道我在做什么,我正在编写一个 Structuremap 约定,它将类实现的所有接口转发到实现(作为单例)。
OpenGenericWithOpenService<T>
不只是实现随意的 IGenericService<>
- 它实现了IGenericService<T>
对于相同的T
作为班级。
展示这一点的最好方法是稍微改变类:
public class OpenGenericWithOpenService<T1, T2> : IGenericService<T1> {}
现在重要的是,当您询问它实现的接口时,您知道可以转换为IGenericService<T1>
但是(巧合除外)not IGenericService<T2>
或任何其他实现。
换句话说,它并不完全开放 - 它被固定到该类具有的相同类型参数。
我一直不太擅长使用泛型术语,但我希望您明白我的意思。IGenericService<>
是一个等待被赋予类型参数的类型;在这种情况下你已经got类型参数 - 它恰好是另一个类型参数!
这是一个将通过的测试:
[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>
相反,它会失败。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)