具有通用约束的泛型类型

时间:2017-04-30 07:36:50

标签: c# generics

我有以下类型:

public interface IContainer<in TKey, out TValue>
{
    TValue Resolve(TKey key);
}

public interface IBuilder<out TContainer, in TKey, out TValue> where 
TContainer : IContainer<TKey, TValue>
{
    TContainer Build();
}

public interface IRegister<in TBuilder, TKey, TValue> where TBuilder : 
IBuilder<IContainer<TKey, TValue>, TKey, TValue>
{
    void Register(TBuilder builder);
}

public interface IServiceMessageHandlerTypeContainer<TService, in 
TServiceMessageHandler> 
    : IContainer<TServiceMessageHandler, ECommand>
    where TServiceMessageHandler : class, IMessageHandler<TService>
{

}

public interface IServiceMessageHandlerTypeContainerBuilder<TService, in 
TServiceMessageHandler, out             TServiceMessageHandlerTypeContainer> 
    : IBuilder<TServiceMessageHandlerTypeContainer, TServiceMessageHandler, 
ECommand>
    where TServiceMessageHandler : class, IMessageHandler<TService>
    where TServiceMessageHandlerTypeContainer : 
IServiceMessageHandlerTypeContainer<TService, TServiceMessageHandler>
{
    void Register<TServiceMessageHandlerType>(ECommand command) 
        where TServiceMessageHandlerType : TServiceMessageHandler;
}

public interface IServiceMessageHandlerTypeRegister<
    TService, 
    TServiceMessageHandler, 
    TServiceMessageHandlerTypeContainer, 
    in TServiceMessageHandlerTypeContainerBuilder> 
    : IRegister<TServiceMessageHandlerTypeContainerBuilder, 
TServiceMessageHandler, ECommand>
    where TServiceMessageHandler : class, IMessageHandler<TService>
    where TServiceMessageHandlerTypeContainer 
    : IServiceMessageHandlerTypeContainer<TService, TServiceMessageHandler> 
    where TServiceMessageHandlerTypeContainerBuilder 
    : IServiceMessageHandlerTypeContainerBuilder<TService, 
TServiceMessageHandler, TServiceMessageHandlerTypeContainer>
{

}

我真的无法得到,为什么TServiceMessageHandlerTypeContainerBuilder的约束在这里不好?

导致IServiceMessageHandlerTypeContainerBuilder

是IBuilder

和IServiceMessageHandlerTypeContainer 是IContainer

你有什么想法吗?

如果我添加禁忌: 其中TServiceMessageHandlerTypeContainerBuilder         :IServiceMessageHandlerTypeContainerBuilder,         IBuilder,TServiceMessageHandler,ECommand&gt;

它有效

但它真的不是我需要的东西

编辑: 编译时错误是:

错误CS0314类型'TServiceMessageHandlerTypeContainerBuilder'不能在泛型类型或方法'IRegister'中用作类型参数'TBuilder'。从'TServiceMessageHandlerTypeContainerBuilder'到'Patterns.DependencyInjection.Builder.IBuilder,TServiceMessageHandler,DataTransmissionServices.Enums.ECommand&gt;'没有装箱转换或类型参数转换。

是否存在与共同和反差的关联?

1 个答案:

答案 0 :(得分:0)

不,它与共同或反方差无关。它与通用参数的约束有关。

TServiceMessageHandlerTypeContainerBuilder的constratin将转到IBuilder<out TContainer, in TKey, out TValue> where TContainer : IContainer<TKey, TValue>

但是从

继承IServiceMessageHandlerTypeRegister
IRegister<TServiceMessageHandlerTypeContainerBuilder,TServiceMessageHandler, ECommand>

约束转到IBuilder,TKey,TValue&gt;。 因为IBuilder,TKey,TValue&gt;无法转换为IBuilder,您收到编译错误。