我在使用Generics从导出类型转换为基类型时遇到问题。
管理字典的类:
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;
}
}
流程上下文的接口:
public interface IProcessContext : IContext<ProcessViewModel>
{
}
我的测试班:
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; }
}
当我尝试注册processContext时,会出现问题:
没有从
'IProcessContext'
到...的隐式引用转换IContext<TViewModelContext>
如何解决此问题?
修改
当我创建一个Foo的继承类时,我可以注册,但我也需要在Foo类上注册。
public interface IAnotherProcessContext : IContext<ProcessTwoViewModel>
{
}
public class InheritedFoo : Foo<ProcessTwoViewModel>
{
public InheritedFoo(IAnotherProcessContext anotherProcessContext)
{
base.ManagerDictionary.Register((int)ContextType.InheritedProcess, anotherProcessContext);
}
}
答案 0 :(得分:2)
您尝试将IContext<T>
视为与T
相关的协变,但该界面未被定义为协变。
要么让界面变得协变,要么改变你的程序,这样你就不会期望IContext<Child>
可以隐式转换为IContext<Parent>
。