简体   繁体   中英

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:

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:

The is no implicit reference conversion from 'IProcessContext' to 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.

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.

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> .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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