泛型参数的 C# 类型转换

标签 c# generics interface

这是一个相当基本的 C# 问题;抱歉,我在其他地方找不到这个。

Object<class> 转换的最佳方式是什么?至Object<interface>

//fake interface
interface ignu {}

//fake class which implements fake interface
class bee : ignu {}

//function which accepts a generic with the interface
function bang(template<bee>) {}

//template type but with a class that implements the interface
template<bar> foo;

//trying to call the function, but compiler complains it can't implicitly convert
bang(foo); 

//compilers complains that it cannot convert from template<bee> to template<ignu>
bang((template<ignu>)bee)

也许我偏离了基地,但这似乎应该可行并且可行,但解决方案却让我无法理解。

编辑:将 mygen 更改为模板,因为我使用两者来指代相同的事物,这令人困惑

编辑:我最终使用了类似于: 砰(bee.Cast());

最佳答案

无法保证 Generic<SubType>实际上可以用作 Generic<BaseType> 的替代品.

考虑一下:

List<int> intlist = new List<int>();
List<object> objlist = intlist; // compile error
objlist.Add("foo"); // what should be in intlist now?

您正在寻找的称为协方差和逆变方差。它们已添加到 c#4 中。

关于泛型参数的 C# 类型转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3559505/

相关文章:

c# - 立方体沿x轴移动问题

generics - Scala:将泛型类型参数约束为另一个参数中的类型

java - 通过接口(interface)实现多重继承

c# - 是否可以将基于接口(interface)的模拟转换为对象?

java - 为什么继承类静态方法而不是接口(interface)静态方法?

c# - VB.net 到 C# 等效于 "AddressOf"

c# - 是否有支持混合 C++ 和 C# 应用程序的崩溃报告服务?

C# 获取给定 T 的类型 Generic<T>

java - 静态方法中的泛型

c# - 带有播放列表的 Visual Studio 测试资源管理器