将Generic实例转换为Base类(Cast Generic instance to Base class)

系统教程 行业动态 更新时间:2024-06-14 17:02:17
将Generic实例转换为Base类(Cast Generic instance to Base class)

我试图尝试诸如此类的东西

void Main() { Temp<Bar> Test = new Foo<InheritedBar>(); } abstract class Temp<T> where T : Bar { } class Foo<T> : Temp<T> where T : Bar { } abstract class Bar { } class InheritedBar : Bar { }

Cannot implicity convert type Foo<InheritedBar> to Temp<Bar>.不起作用,错误Cannot implicity convert type Foo<InheritedBar> to Temp<Bar>.

但是, Temp<InheritedBar> Test = new Foo<InheritedBar>(); 和Temp<Bar> Test = new Foo<Bar>();

两者都有效。 为什么即使InheritedBar继承自Bar,它也不能通过泛型强制转换为它?

我在wpf页面中使用泛型类型,它不能创建为泛型,因此我不能将T作为其类型传递。 我只想要Temp的这个功能,而不是任何派生版本的功能。 有一个更好的方法吗?

I am trying to attempt something such as

void Main() { Temp<Bar> Test = new Foo<InheritedBar>(); } abstract class Temp<T> where T : Bar { } class Foo<T> : Temp<T> where T : Bar { } abstract class Bar { } class InheritedBar : Bar { }

The cast does not work, with the error Cannot implicity convert type Foo<InheritedBar> to Temp<Bar>.

However, Temp<InheritedBar> Test = new Foo<InheritedBar>(); and Temp<Bar> Test = new Foo<Bar>();

Both work. Why even though InheritedBar inherits from Bar, it can't be cast to it through generics?

I am using the generic type in a wpf Page, which can not be created as a generic so I can't pass T as its type. I only want the functionality at the time of this of Temp, not any of the derived versions functionality. Is there a better way to do this?

最满意答案

您尝试使用的概念是协方差 ( MSDN上的完整说明)

简短的回答是你需要使用标记你的泛型参数; 但是你只能在一个接口上做到这一点(在你的情况下从一个抽象类改变)。 此外,根据您的方法参数和返回值,您可能无法将您的界面标记为协变。

interface Temp<out T> where T : Bar { }

The concept you are attempting to utilize is covariance (full explanation on MSDN)

The short answer is that you need to use mark your generic parameter with out; but you can only do that on an interface (changing from an abstract class in your case). Also, depending on your method parameters and return values, you may not be able to mark your interface as covariant.

interface Temp<out T> where T : Bar { }

更多推荐

本文发布于:2023-04-21 18:24:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/dzcp/94808f8b44128bdbcf423aa164a9a69e.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:转换为   实例   Generic   Base   class

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!