我想不通。问题是距离、球杆、cleanclub、洞、分数和标准杆都说由于保护级别而无法访问,我不知道为什么,因为我认为我做的一切都是正确的。
namespace homeworkchap8
{
public class Clubs
{
protected string club;
protected string distance;
protected string cleanclub;
protected string scores;
protected string par;
protected string hole;
public string myclub
{
get { return club; }
set {club = value; }
}
public string mydistance
{
get { return distance; }
set { distance = value; }
}
public string mycleanclub
{
get { return cleanclub; }
set { cleanclub = value; }
}
public string myscore
{
get { return scores; }
set { scores = value; }
}
public string parhole
{
get { return par; }
set { par = value; }
}
public string myhole
{
get { return hole; }
set { hole = value;}
}
}
}
这是派生类:
namespace homeworkchap8
{
public class SteelClubs : Clubs, ISwingClub
{
public void SwingClub()
{
Console.WriteLine("You hit a " + myclub + " " + mydistance);
}
public void clean()
{
if (mycleanclub != "yes")
{
Console.WriteLine("your club is dirty");
}
else
{
Console.WriteLine("your club is clean");
}
}
public void score()
{
Console.WriteLine("you are on hole " + myhole + " and you scored a " +
myscore + " on a par " + parhole);
}
}
}
这是界面:
namespace homeworkchap8
{
public interface ISwingClub
{
void SwingClub();
void clean();
void score();
}
}
主要代码如下:
namespace homeworkchap8
{
class main
{
static void Main(string[] args)
{
SteelClubs myClub = new SteelClubs();
Console.WriteLine("How far to the hole?");
myClub.distance = Console.ReadLine();
Console.WriteLine("what club are you going to hit?");
myClub.club = Console.ReadLine();
myClub.SwingClub();
SteelClubs mycleanclub = new SteelClubs();
Console.WriteLine("\nDid you clean your club after?");
mycleanclub.cleanclub = Console.ReadLine();
mycleanclub.clean();
SteelClubs myScoreonHole = new SteelClubs();
Console.WriteLine("\nWhat hole are you on?");
myScoreonHole.hole = Console.ReadLine();
Console.WriteLine("What did you score on the hole?");
myScoreonHole.scores = Console.ReadLine();
Console.WriteLine("What is the par of the hole?");
myScoreonHole.par = Console.ReadLine();
myScoreonHole.score();
Console.ReadKey();
}
}
}
最佳答案
在您的基类 Clubs
中,以下内容被声明为 protected
- 俱乐部;
- 距离;
- 清洁俱乐部;
- 分数;
- 标准;
- 洞;
这意味着这些只能由类本身或派生自 Clubs
的任何类访问。
在您的 main
代码中,您尝试在类本身之外访问这些。例如:
Console.WriteLine("How far to the hole?");
myClub.distance = Console.ReadLine();
您已经(有些正确地)为这些变量提供了公共(public)访问器。例如:
public string mydistance
{
get
{
return distance;
}
set
{
distance = value;
}
}
这意味着您的主要代码可以更改为
Console.WriteLine("How far to the hole?");
myClub.mydistance = Console.ReadLine();
关于c# - 由于其保护级别而无法访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6125077/