铸造泛型和泛型类型 [英] Casting generics and the generic type

查看:144
本文介绍了铸造泛型和泛型类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑,我有以下3类/接口:

Consider, I have the following 3 classes / interfaces:

class MyClass<T> { }

interface IMyInterface { }

class Derived : IMyInterface { }

和我希望能够投 MyClass的<衍生> MyClass的< IMyInterface的> ,反之亦然:

And I want to be able to cast a MyClass<Derived> into a MyClass<IMyInterface> or visa-versa:

MyClass<Derived> a = new MyClass<Derived>();
MyClass<IMyInterface> b = (MyClass<IMyInterface>)a;



但我得到的编译器错误,如果我尝试:

But I get compiler errors if I try:

Cannot convert type 'MyClass<Derived>' to 'MyClass<IMyInterface>'   

我敢肯定有一个很好的理由,为什么我不能这样做,但我想不出之一。

I'm sure there is a very good reason why I cant do this, but I can't think of one.

至于为什么我想做到这一点 - 我想象的场景是之一,即你最好要与 MyClass的<的实例来工作;衍生> ,以避免大量讨厌的类型转换,然而,你需要你的实例传递给接受一个接口 MyClass的< IMyInterface的方式>

As for why I want to do this - The scenario I'm imagining is one whereby you ideally want to work with an instance of MyClass<Derived> in order to avoid lots of nasty casts, however you need to pass your instance to an interface that accepts MyClass<IMyInterface>.

所以我的问题是双重的:

So my question is twofold:


  • 我为什么不能投这两种类型之间

  • 有保留的任何方式与实例工作的正派 MyClass的<衍生> 同时仍然能够投成 MyClass的<这一点; IMyInterface的>

  • Why can I not cast between these two types?
  • Is there any way of keeping the niceness of working with an instance of MyClass<Derived> while still being able to cast this into a MyClass<IMyInterface>?

推荐答案

这不起作用,因为C#只支持的接口类型参数的协方差和代表。如果你的类型参数只存在于输出位置(即你只能从你的类返回它的实例,并且不接受它作为参数),你可以创建这样一个接口:

This does not work because C# only supports covariance on the type parameters of interfaces and delegates. If your type parameter exists only in output positions (i.e. you only return instances of it from your class and don't accept it as an argument) you could create an interface like this:

interface IClass<out T> { }
class MyClass<T> : IClass<T> { }



这将允许你这样做:

Which would allow you to do this:

IClass<Derived> a = new MyClass<Derived>();
IClass<IMyInterface> b = a;



老实说这是最接近你会得到这需要C#4编译工作

Honestly that is about as close as you are going to get and this requires the C# 4 compiler to work.

这篇关于铸造泛型和泛型类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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