Inheritance : does not contain a definition for and no extension method accepting a first argument

后端 未结 2 956
醉梦人生
醉梦人生 2021-01-21 01:23
abstract class Parent
{
        protected string attrParent;

        public AttrParent { get; protected set }

        public Parent(string sParent)
        {
                  


        
相关标签:
2条回答
  • 2021-01-21 01:49

    The moment you assign Child instance to variable typed as Parent you can only access members declared on Parent.

    You'd have to downcast it back to Child to access Child-only members:

    Parent p = new Child();
    
    Child c = (Child)p;
    c.AttrChild = "hello";
    

    That cast might fail at runtime, because there might be a different class that inherits Parent.

    0 讨论(0)
  • 2021-01-21 02:10

    A parent instance can only access methods avaliable in the parent class, If you want to access the child methods you need to create a child class. The problem if that you are trying to access the child methods from the parent class.

    With inheritance if you wish to call methods in the child class you will need to make a new instance of child class. The purpose of that a parent can have multiple child classes inheriting from it and if the code in your example worked then it would cause problems when a parent has multiple child classes.

    0 讨论(0)
提交回复
热议问题