简体   繁体   中英

Child Class Properties Not Visible

I am fairly new to c# and very new to abstract classes. Below is an example of the code I am writing. I instantiate my object with Parent obj = new Child2(); or Parent obj = new Child3();

Note that the purpose of this is Child 2 and 3 have different properties but some common, overloaded methods.

My problem is that I can not see any properties in the child class

if I have not described the question in enough detail, please let me know and I will elaborate

namespace ns
{
    public class Parent
    {
        public abstract DataTable ImportToDataTable()

    }

    public class Child2 : Parent
    {
        public DelimitedFileDetail InputFile = new DelimitedFileDetail();
        public string PropertyforChild1 { get; set; }
        public override DataTable ImportToDataTable() { .....code }

    }

    public class Child3 : Parent
    {
        public string PropertyforChild2 { get; set; }
        public override DataTable ImportToDataTable() { .....code }

    }

    public class DelimitedFileDetail : Child2
    {
        public string Name { get; set; }
        public ImportTypes FileType { get; set; }
        public List<FieldDefinitions> FieldList = new List<FieldDefinitions>();
    }

}

Well, when you declare the variable in c# with the Parent type, intelisense won't show you the properties of the child. If you want to use the specific properties of the children you need to declare the variable with the type of the specific children.

So instead of doing:

Parent obj = new Child2();

You should do:

Child2 obj = new Child2();

And so for...

You can't see any properties of the child class because you've told the compiler that obj is of type Parent . If you want to see the properties of the child class you can cast obj to the true type:

Parent obj = new Child2();
string str = ((Child2)obj).PropertyforChild2;

This is, of course, not ideal code. Mostly because then you have to know that obj is of type Child2 and if you know that, why not just give obj the type Child2 ?

You should define your Parent class to be an interface instead of abstract class or base class for that matter

This way your child classes can implement the interface. Then you should use the interface variable to reference child classes/implementations.

Is there a reason you have defined Parent as abstract class? An interface should do since you haven't implemented any abstract members anyway

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