类和具有泛型类型的接口的C#3.0隐式转换错误 [英] C# 3.0 implicit cast error with class and interfaces with generic type

查看:89
本文介绍了类和具有泛型类型的接口的C#3.0隐式转换错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我实现了一些依赖关系(这是MVP模式的一部分)。现在,当我尝试执行转换时,VS会通知错误。

I implemented a few dependencies (which are the part of MVP pattern). Now, when I try to perform casting, VS informs about an error.

定义:

interface IView
{
     void setPresenter(IPresenter<IView> presenter);
}

interface IViewA : IView
{
}

interface IPresenter<T> where T : IView
{
    void setView(T view);
}

class PresenterA : IPresenter<IViewA>
{
}

隐式转换:

IPresenter<IView> presenter = new PresenterA();

编译错误:
无法将类型 PresenterA隐式转换为 IPresenter。存在显式转换(是否缺少转换?)

Compile error: Cannot implicitly convert type 'PresenterA' to 'IPresenter'. An explicit conversion exists (are you missing a cast?)

显式转换:

IPresenter<IView> presenter = (IPresenter<IView>)new PresenterA();

运行时错误:InvalidCastException

Run-time error: InvalidCastException

我如何解决这个问题以保持这种观念?具有泛型类型的构想(我以前的概念没有它)。我已经尝试了其他文章中提到的方差和方差问题(输入和输出),但是也存在错误(在VS 2010下)。

How can I solve it to keep this conception? Conception with generic type (my previous one is without it). I've tried variance and contravariance issue (in and out) as mentioned in the others posts, but there was errors too (under VS 2010).

推荐答案

IViewA 源自 IView 的事实并不自动意味着 IPresenter< IViewA> IPresenter< IView> 派生。实际上, IPresenter< IViewA> IPresenter< IView> 是两个不同的类型,它们之间没有继承关系。他们唯一的祖先是 object

The fact that IViewA derives from IView does not automatically mean that IPresenter<IViewA> derives from IPresenter<IView>. In fact IPresenter<IViewA> and IPresenter<IView> are two distinct types that do not have an inheritance relation between them. Their only common ancestor is object.

让我们看一个例子。假设我们有一个 Animal 类,一个 Cat 类是从 Animal 和从 Animal 派生的类 Dog 。现在,我们声明两个列表

Let's look at an example. Assume that we have a class Animal, a class Cat deriving from Animal and a class Dog deriving from Animal. Now let's declare two lists

List<Animal> animals;
List<Cat> cats = new List<Cat>();

我们还假设以下分配是可能的:

And let's also assume that the following assignment was possible:

animals = cats;
animals.Add(new Cat()); // OK
animals.Add(new Dog()); // Ooops!

此列表实际上是猫列表,我们正在尝试添加狗!因此,不允许将 List< Animal> List< Cat> 这两种类型进行赋值兼容。

The list is in reality a cats list and we are trying to add a dog! Therefore the two types List<Animal> and List<Cat> are not allowed to be assignment compatible.

这篇关于类和具有泛型类型的接口的C#3.0隐式转换错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆