簡體   English   中英

C#多態性錯誤:由於其保護級別而無法訪問

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

我正在嘗試一個多態示例,但是我的代碼中出現以下錯誤:

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();
}

我得到一個錯誤,即派生類構造函數“由於其保護級別而無法訪問”。 我不知道為什么。 我用隱式派生構造函數工作的另一個例子。

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

這有效並且具有幾乎相同的代碼。 構造函數“ Circle()”,“ Hexagon()”這次不需要任何保護級別。 有任何想法嗎?

CPolygon() {} 

那是一個private構造函數。
您不能在課堂外稱呼它。

由於派生類必須始終從其基類調用構造函數,因此會出現錯誤。

C#的默認符號可見性是私有的。 如果不將“ public”放在類或函數定義的前面,則它具有私有可見性,這意味着其他任何類都看不到該符號。

CPolygon類是Public,但是您沒有為CRectangle和CTriangle定義保護級別,如果將兩個派生類設置為public,仍然會收到錯誤消息嗎?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM