Casting a interface derived class to another deriv

2020-05-07 02:00发布

问题:

I am trying to accomplish a way to cast a given object that is derived from an interface to a different type that is also derived from the same interface. This to prevent having to completely rebuild the object.

interface IItem
{
}

class FryingPan : IItem
{
}

class CookingPan : IItem
{
}

But here is the catch, I don't 'know' what type I am casting to. I only know by a type variable. This is set from a combobox.

Type SelectedItem { get; set; }

Can this be done ( preferably without having to implement IConvertable )

回答1:

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
{ }

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. ;-)

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.



标签: c# casting