在共享相同接口的类之间进行转换 [英] Casting between classes that share the same interface

查看:84
本文介绍了在共享相同接口的类之间进行转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个接口 IHeaderRow IDetailRow

然后我有一个实现这两个接口的对象 RawRow:IHeaderRow,IDetailRow

I then have an object that implements both RawRow:IHeaderRow, IDetailRow

然后我需要将其转换为实现 IHeaderRow HeaderRow

I then need to cast it to HeaderRow which implements IHeaderRow.

但是当我尝试时,它最终会为null或给出异常。

But when I try, it ends up being null or giving an exception.

我可以投射 ObjectRawRow IHeaderRow IDetailRow

var ObjectIHeaderRow = ObjectRawRow as IHeaderRow;
var ObjectIDetailRow = ObjectRawRow as IDetailRow;

但是我无法将 ObjectRawRow 强制转换为 HeaderRow ObjectIHeaderRow HeaderRow

But I can not cast ObjectRawRow to HeaderRow , or ObjectIHeaderRow to HeaderRow.

它引发错误无法转换源类型 IA定位到类型'A'

我需要将其转换为实际的类 HeaderRow

I need to cast it into the actual class HeaderRow.

有想法吗?

编辑:

即使设置了明确的强制转换关心这个问题,我想我会向想知道为什么的人提供答案。

Even though setting up an explicit cast took care of the issue I thought I'd provide an answer to the people wondering, WHY I was doing what I was.

简而言之,我正在按顺序处理文件。逐行。我将行读入RawRow,直到查看一些值,我才真正知道行将是哪种类型。然后,我想将其强制转换为正确的类型。

In short, I'm sequentially processing a file. Line by line. I read the row into RawRow, and until I look at a few values, I don't actually know what type of row it is going to be. I then wanted to cast it to the proper type.

推荐答案

您只能将对象隐式转换为它们继承或实现的类型-由于 RawRow 并非源自 HeaderRow ,因此不可能。

You can only implicitly cast objects to types they inherit from or implement - since RawRow doesn't derive from HeaderRow, it's not possible.

根据您的要求,您可以通过编写显式转换运算符,创建了一个 HeaderRow 构造函数,该构造函数接受 RawRow 作为其原型,或修改代码以在 IHeaderRow 上运行。

Depending on your requirements, you could overcome this by writing an explicit conversion operator, creating a HeaderRow constructor that accepts a RawRow as its prototype, or by modifying your code to operate on an IHeaderRow.

这篇关于在共享相同接口的类之间进行转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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