不同类型的数组,如何知道什么对他们投把他们从数组时?数组、不同类型

2023-09-04 11:45:04 作者:凉栀

假设通用列表键入分组,拿着自定义类延伸的分组,如 LoginPacket 或< STRONG> ChatPacket

Assume a generic List of type Packet, holding custom classes extending Packet, such as LoginPacket or ChatPacket.

比方说,我在列表中把这些。当我带他们出去,最具体类型的每个将是分组。我想这些投到他们的更具体的类型,虽然,放回原来的 LoginPacket 或 ChatPacket 或放回不论其原来的类型为。

Let's say I put these in a list. When I take them out, the most 'specific' type each will be is Packet. I want to cast these into their more specific types though, back into their original LoginPacket or ChatPacket or back into whatever their original types were.

问:我怎样才能做到这一点。

Question: How can I do this?

参考:How以编程方式投在运行时的对象?

所以......好像如果这些自定义类共享一个通用的接口,它可以解决铸造问题?但即便如此,我的类不能都共享一个接口。我需要建立在类在接口接口和类。所以...我将如何做到这一点?很抱歉,如果这个问题不那么准确。不知道如何表达我的确切问题。

So...it seems like if these custom classes share a common interface, it would solve the casting problem? But if so, my classes can't all share one interface. I need to build interfaces upon interfaces and classes upon classes. So...how would I do this? Sorry if this question isn't so accurate. Not sure how to articulate my exact issue.

推荐答案

您的可以的有整个一长串的if / else或开关

You could have a whole long list of if/else or a switch

if (item is ChatPacket)
{
    // cast
}
else if (...)
{
    // cast
}
else ...

不过,这可以成为笨拙。

However, that can become unwieldly.

您不妨重温类的设计。通过具有名单,其中,数据分组&gt; ,你有效地阐明的你不关心派生的孩子的之间的区别,至少在以下方面其独特的API。

You may wish to revisit your class design. By having a List<Packet>, you're effectively stating you do not care about the differences between the derived children, at least in terms of their unique APIs.

在换句话说,如果你的设计

In other words, if your design is

class Packet { public void Foo() { } }
class ChatPacket : Packet { public void Bar() { } }

您是说你只关心能够访问美孚()

You're saying you only care about being able to access Foo().

如果您的执行的关心差异,或许你可以EX preSS通过在基础抽象的或虚拟的方法和被覆盖的行为,在孩子们这些差异与基因多态性。因此,你仍然有基类的集合,但你仍然可以得到所指定的每一个孩子的自定义行为。

If you do care about differences, perhaps you can express those differences with polymorphism via abstract or virtual methods in the base and overriden behaviors in the children. Therefore you still have a collection of base classes, but you still get the custom behaviors as specified by each child.

class Packet { public virtual void Foo() { } }
class ChatPacket : Packet { public override void Foo() { } }

在这里,你可以调用只需调用美孚()。无铸造必要的。