在我看来,这是一个应该通过的测试,但事实并非如此。
[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> { }typeof(IGenericService<>)?
Type t = typeof(OpenGenericWithOpenService<>)如何获得Type t = typeof(OpenGenericWithOpenService<>)我通常很好奇,但是如果您想知道我在做什么,我正在编写一个结构映射约定,它将一个类实现的所有接口转发到实现(作为一个单例)。
发布于 2010-04-20 20:31:35
OpenGenericWithOpenService<T>不只是实现一个任意的IGenericService<> -它实现与类相同的T的IGenericService<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>,它将失败。
https://stackoverflow.com/questions/2678336
复制相似问题