简体   繁体   English

C#没有使用泛型从'B'到'A'的隐式引用转换

[英]C# The is no implicit reference conversion from 'B' to 'A' using Generics

I'm with problems to convert from the type derived to base type using Generics. 我遇到了使用泛型从派生类型转换为基本类型的问题。

Class to manage the dictionary: 管理字典的类:

public class ManagerDictionary<TContext>
{
    public ManagerDictionary()
    {    
        this.Dictionary = new Dictionary<int, TContext>();
    }

    public IDictionary<int, TContext> Dictionary { get; private set; }

    public void Register<TSubContext>(int context, TSubContext subContext) where TSubContext : TContext
    {
        this.Dictionary[context] = subContext;
    }
}

Interface of the Process context: Process上下文的接口:

public interface IProcessContext : IContext<ProcessViewModel>
{
}

My test class: 我的测试课:

public class Foo<TViewModelContext> where TViewModelContext : ViewModeBase
{
    public Foo(IProcessContext processContext)
    {
        // Create de Dictionary Manager.
        this.ManagerDictionary = new ManagerDictionary<IContext<TViewModelContext>>();

        // Register the process context on dictionary.
        // The error is occurring here: The is no implicit reference conversion from 'IProcessContext' to 'IContext<TViewModelContext>'
        this.ManagerDictionary.Register((int)ContextType.Process, processContext);
    }

    protected ManagerDictionary<IContext<TViewModelContext>> ManagerDictionary { get; set; }
}

When I try register the processContext, the problem occurs: 当我尝试注册processContext时,出现问题:

The is no implicit reference conversion from 'IProcessContext' to IContext<TViewModelContext> 'IProcessContext'IContext<TViewModelContext>无隐式引用转换

How can I resolve this problem? 我该如何解决这个问题?

Edit: 编辑:

When I Create a inherited class of the Foo, I can register, but I need register on Foo class too. 创建Foo的继承类时,我可以注册,但是我也需要在Foo类上注册。

public interface IAnotherProcessContext : IContext<ProcessTwoViewModel>
{
}

public class InheritedFoo : Foo<ProcessTwoViewModel>
{
    public InheritedFoo(IAnotherProcessContext anotherProcessContext)
    {
        base.ManagerDictionary.Register((int)ContextType.InheritedProcess, anotherProcessContext);
    }
}

You're trying to treat IContext<T> as if it's covariant with respect to T , but that interface isn't defined as being covariant. 您正在尝试将IContext<T>视为相对于T是协变的,但是未将该接口定义为协变的。

Either make the interface be covariant, or alter your program such that you never expect an IContext<Child> to be implicitly convertible to an IContext<Parent> . 要么使该接口是协变的,要么更改程序,以使您永远不会期望IContext<Child>隐式转换为IContext<Parent>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM