首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >开放通用接口类型的开放实现不等于接口类型?

开放通用接口类型的开放实现不等于接口类型?
EN

Stack Overflow用户
提问于 2010-04-20 20:19:38
回答 1查看 1.4K关注 0票数 10

在我看来,这是一个应该通过的测试,但事实并非如此。

代码语言:javascript
复制
[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<>)?

  1. 为什么没有通过?
  2. 给定Type t = typeof(OpenGenericWithOpenService<>)如何获得Type t = typeof(OpenGenericWithOpenService<>)

我通常很好奇,但是如果您想知道我在做什么,我正在编写一个结构映射约定,它将一个类实现的所有接口转发到实现(作为一个单例)。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2010-04-20 20:31:35

OpenGenericWithOpenService<T>不只是实现一个任意的IGenericService<> -它实现与类相同的TIGenericService<T>

展示这一点的最好方法是稍微修改类:

代码语言:javascript
复制
public class OpenGenericWithOpenService<T1, T2> : IGenericService<T1> {}

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

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

我从来没有很好的泛型术语,但我希望你明白我的意思。IGenericService<>是一种等待被赋予类型参数的类型;在本例中,您得到了类型参数--它恰好是另一个类型参数!

这里有一项考试将通过:

代码语言:javascript
复制
[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>,它将失败。

票数 7
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/2678336

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档