不能访问由于c#类的保护级别
本文关键字:保护 访问 不能 | 更新日期: 2023-09-27 18:17:45
我正在构建一些具有继承的类,这些类与派生类方法一起工作,并且我在应用程序中遇到了保护问题。这里是获得错误的一个类的一小部分源代码。
代码:
class Cone : Circle
{
private double height; // Data members
public Cone() : base() // Default constructor with explicit call
{ // to base (Circle) default constructor
this.Label = "Unlabeled Cone";
this.height = 0.0;
}
public Cone(Point centerValue, double radiusValue, double heightValue):
base(centerValue, radiusValue) // Initializing constructor with explicit
{ // call to base (Circle) initializing construtor
this.Label = "Unlabeled Cone";
this.Height = heightValue;
}
public Cone(Point centerValue, double radiusValue, double heightValue, string labelValue):
base(centerValue, radiusValue, labelValue) // Initializing constructor with explicit
{ // call to base (Circle) initializing construtor
this.Height = heightValue;
}
public Cone(Cone sourceCone) // Copy constructor
{
this.Copy(sourceCone);
}
public double Height // Define read/write Height property
{
get
{
return this.height;
}
set
{
if (value >= 0.0)
this.height = value;
else
{
Console.WriteLine("Runtime error: {0} can not be assigned to a Height property'n", value);
ConsoleApp.Exit();
}
}
}
下面是它的派生类:
public class Circle : object
{
private Point center; // Data member
private double radius; // Data member
private string label; // Data member
public Circle()
{
this.center = new Point();
this.radius = 0.0;
this.label = "Unlabeled Circle";
}
public Circle(Point centerValue, double radiusValue)
{
this.center = new Point(centerValue);
this.Radius = radiusValue;
this.label = "Unlabeled Circle";
}
public Circle(Point centerValue, double radiusValue, string labelValue)
{
this.center = new Point(centerValue);
this.Radius = radiusValue;
this.Label = labelValue;
}
public Circle(Circle sourceCircle) // Copy constructor
{
this.center = new Point();
this.Copy(sourceCircle);
}
public Point Center // Define read/write Center property
{
get
{
return this.center;
}
set
{
this.center = value.Clone();
}
}
类的添加时间更长,但在我的主机应用中,由于其保护级别,我一直无法访问Cone。我正在努力看到的东西是私有的,这是保持它能够从控制台应用程序访问。如果你想看到完整的类代码,这里是在pastebin…源代码里
你的类声明没有可访问性级别:
class Cone : Circle
如果您不提供访问级别,它将默认为最低访问级别(最受限制)。用途:
public class Cone
如果在不同的命名空间,则声明cone类为public;如果在相同的命名空间,则声明cone类为internal。
我建议你把它们放在同一个命名空间的一个单独的文件中(因为它们都是形状),并在使用它的代码中导入特定的命名空间