简体   繁体   中英

Downcast an inherited class to base class

Let say i have a base class

class baseClass
{  }

And another class that inherit from that baseClass

class foo : baseClass
{  }

I tryed to cast it back directly (baseClass)foo but the compiler say it cannot be done.

Is there a way from foo to get only the baseClass ?

foo is a baseClass you don't need any casting. And your code should work without any problems:

var foo = new foo();
baseClass x = (baseClass) foo;

If you derive a class A from class B you can always refer to A as if it were B . Of course this is not true in the revese case. In general you can always refer down the chain of inherited classes.

If the compiler complain on such a thing, it could just mean you have several baseClass defined in several Namespace and you're actually not referencing the right baseClass.

Check your Namespaces it should solve your bug.

Here a working example with different Namespaces

namespace BaseNameSpace
{
    public class BaseClass
    {
        public string Name { get; set; }
    }
}

namespace TestNameSpace.Class
{

    public class TestClass : BaseClass
    {
        public string Address { get; set; }
    }
}

Use :

TestClass test1  = new TestClass();
BaseClass b = test1;

Ensure that there is the correct using :

using BaseNameSpace;
using TestNameSpace.Class;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM