加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 打开通用接口类型的开放实现不等于接口类型?

发布时间:2020-12-15 06:51:17 所属栏目:百科 来源:网络整理
导读:这是一个测试,在我看来,应该过去,但不是. [TestMethod]public void can_get_open_generic_interface_off_of_implementor(){ typeof(OpenGenericWithOpenService).GetInterfaces().First() .ShouldEqual(typeof(IGenericService));}public interface IGeneric
这是一个测试,在我看来,应该过去,但不是.
[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> { }

>为什么不通过?
>给定类型t = typeof(OpenGenericWithOpenService?)如何获取typeof(IGenericService?)?

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

解决方法

OpenGenericWithOpenService< T>不实现任意的IGenericService<> – 它实现IGenericService< T>与同级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>相反,它会失败.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读