开放实现的开放通用接口类型不等于接口类型吗? [英] Open generic interface types of open implementation don't equal interface type?

查看:38
本文介绍了开放实现的开放通用接口类型不等于接口类型吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我看来,这是一项应该通过但没有通过的测试.

Here's a test that should, in my opinion be passing but is not.

[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> { }

  1. 为什么这个不通过?
  2. 给出类型t = typeof(OpenGenericWithOpenService<>)如何获取typeof(IGenericService<>)?
  1. Why does this not pass?
  2. Given Type t = typeof(OpenGenericWithOpenService<>) how do I get typeof(IGenericService<>)?

我通常很好奇,但是如果您想知道我在做什么,我正在写一个Structuremap约定,该约定将由类实现的所有接口转发给实现(作为单例).

I'm generally curious, but if you're wondering what I'm doing, I'm writing a Structuremap convention that forwards all interfaces implemented by a class to the implementation (as a singleton).

推荐答案

OpenGenericWithOpenService< T> 并不仅实现了任意 IGenericService<> -它为与类相同的 T 实现 IGenericService< T> .

OpenGenericWithOpenService<T> doesn't implement just an arbitrary IGenericService<> - it implements IGenericService<T> for the same T as the class.

证明这一点的最好方法是稍微改变班级:

The best way to show this is to change the class slightly:

public class OpenGenericWithOpenService<T1, T2> : IGenericService<T1> {}

现在很重要的一点是,当您要求为其实现的接口时,您知道可以转换为 IGenericService< T1> ,但是(巧合的是)不是 IGenericService< T2> 或任何其他实现.

Now it's important that when you ask that for the interfaces it implements, you know that you can convert to IGenericService<T1> but (coincidences aside) not IGenericService<T2> or any other implementation.

换句话说,它不是完全开放的-固定在类具有的相同类型参数上.

In other words, it's not entirely open - it's pinned down to the same type argument that the class has.

我对泛型术语从未有过很好的了解,但我希望您明白我的意思. IGenericService<> 是一种类型,需要等待为其提供类型实参;在这种情况下,您获得了类型参数-它恰好是另一个类型参数!

I've never been very good with the generics terminology, but I hope you see what I mean. IGenericService<> is a type waiting to be given a type argument; in this case you've got the type argument - it just happens to be another type parameter!

这是一项将通过的测试:

Here's a test which will pass:

[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> ,它将失败.

If you change the class to implement (say) IGenericService<int> instead, it will fail.

这篇关于开放实现的开放通用接口类型不等于接口类型吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆