gpt4 book ai didi

C# 多态错误 : is inaccessible due to its protection level

转载 作者:行者123 更新时间:2023-11-30 13:39:13 30 4
gpt4 key购买 nike

我正在尝试一个多态性示例,但我的代码中出现以下错误:

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# 多态错误 : is inaccessible due to its protection level,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12899916/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com