简体   繁体   中英

C# Polymorphism Error : is inaccessible due to its protection level

I was trying a polymorphism example but I got the following errors in my code :

public class CPolygon 
{
    CPolygon() {} 
    public int width {get; set;} 
    public int height {get; set;}        
    public virtual int area(){ return 0; } 
}

class CRectangle: CPolygon 
{ 
    public CRectangle() {} //'Lista.CPolygon.CPolygon()' is inaccessible due to its protection level

    public override int area ()
    { 
        return (width * height); 
    }
}

class CTriangle: CPolygon //'Lista.CPolygon.CPolygon()' is inaccessible due to its protection level
{
    CTriangle() {} 

    public override int area ()
    { 
        return (width * height / 2); 
    }
}

static void Main(string[] args)
{
    CTriangle triangle= new CTriangle();
    triangle.height=5;
    triangle.width=6;
    int area1 = triangle.area();
}

I get the error that the derived class constructors "is inaccessible due to its protection level". I have no idea why. I did another example with implicit derived constructors which worked.

abstract class Shape
{
    public Shape(string name = "NoName")
    { PetName = name; }
    public string PetName { get; set; }
    public abstract void Draw();
}

class Circle : Shape
{
    public Circle() {}
    public Circle(string name) : base(name) {}
    public override void Draw()
    {
    Console.WriteLine("Drawing {0} the Circle", PetName);
    }
}

class Hexagon : Shape
{
    public Hexagon() {}
    public Hexagon(string name) : base(name) {}
    public override void Draw()
    {
    Console.WriteLine("Drawing {0} the Hexagon", PetName);
    }
}

This works and has almost the same code. The constructors "Circle()" , "Hexagon()" don't require any protection level this time. Any ideas?

CPolygon() {} 

That's a private constructor.
You cannot call it outside the class.

Since derived classes must always call a constructor from their base classes, you get an error.

C#'s default symbol visibility is private. If you don't put "public" in front of the class or function definition, it has private visibility, which means no other class can see that symbol.

CPolygon类是Public,但是您没有为CRectangle和CTriangle定义保护级别,如果将两个派生类设置为public,仍然会收到错误消息吗?

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