Geo*_*uer 10 .net c# generics reflection
这是一个测试,在我看来应该通过,但不是.
[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> { }
Run Code Online (Sandbox Code Playgroud)
Type t = typeof(OpenGenericWithOpenService<>)我如何获得typeof(IGenericService <>)?我一般很好奇,但是如果你想知道我在做什么,我正在编写一个Structuremap约定,它将类实现的所有接口转发给实现(作为单例).
OpenGenericWithOpenService<T>不实现任意 IGenericService<> - 它实现与类IGenericService<T>相同T.
显示此信息的最佳方法是稍微更改类:
public class OpenGenericWithOpenService<T1, T2> : IGenericService<T1> {}
Run Code Online (Sandbox Code Playgroud)
现在重要的是,当你要求它实现的接口时,你知道你可以转换为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);
}
Run Code Online (Sandbox Code Playgroud)
如果你改变要实现的类(比如说)IGenericService<int>,它将会失败.