且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将接口派生类转换为另一个派生类

更新时间:2023-01-07 15:11:37

如果您要执行的操作是将CookingPan转换为FryingPan,则无法完成。一个将不得不从另一个派生出来。想象一下;

If what you are trying to do is cast CookingPan to FryingPan, it can't be done. One would have to derive from the other to cast. Imagine;

interface IFruit
{ }

class Apple : IFruit
{ }

class Orange : IFruit
{ }

,苹果绝对不能是橙色,反之亦然。但是,您可以将苹果或橘子浇铸到IFruit,因为它们都具有相同的祖先。或者,如果您是一个疯狂的科学家,也许您可​​以将苹果转换为橙色。 ;-)

Obviously, an apple can never be an orange, and vice-versa. However, you could cast either an Apple or an Orange to IFruit, as they both share that common ancestor. Or, if you are a mad scientist, perhaps you could convert an apple to an orange somehow. ;-)

我想说的是您以错误的方式来解决问题。如果您需要根据IItem的.Type对其执行某些特定操作,那么您已经具有该信息。如果需要一些通用的排序条件,请考虑将其作为所有派生类型的共同祖先移至基类/接口。

I would say that you are approaching your problem in the wrong way. If you need to perform some specific action on an IItem depending on its .Type, then you already have that information. If you need some common sort criteria, consider moving it to the base class/interface as a common ancestor for all derived types.