我是C#的新手并在书中经历了一个例子。该示例基于创建卡类,卡组类和运行这两个类的另一个CardClient项目。
我在编译时遇到错误。第一个错误是:
可访问性不一致:属性类型'ConsoleApplication1.Card.Suit'的可访问性低于属性'ConsoleApplication1.Card.suit'
下一个错误:
找不到类型或命名空间名称“Deck”(您是否缺少using指令或程序集引用?)
两者的代码如下:
namespace ConsoleApplication1
{
class Card
{
public Suit suit
{
get
{
return suit;
}
}
public Rank rank { get; }
enum Suit
{
HEART,
SPADE,
CLUB,
DIAMOND
}
enum Rank
{
ACE,
TWO,
THREE,
FOUR,
FIVE,
SIX,
SEVEN,
EIGHT,
NINE,
TEN,
JACK,
QUEEN,
KING
}
private Card()
{
}
public Card(Suit suit, Rank rank)
{
this.suit = suit;
this.rank = rank;
}
public override string ToString()
{
return suit + " of " + rank;
}
}
class Deck
{
private Card[] cards;
public Deck()
{
cards = new Card[52];
for (int suitVal = 0; suitVal < 4; suitVal++)
{
for (int rankVal = 1; rankVal < 14; rankVal++)
{
cards[suitVal * 13 + rankVal - 1] = new cards[(Suit)suitVal, (Rank)rankVal];
}
}
}
public Card GetCard(int cardLocation)
{
if (cardLocation >= 0 && cardLocation <= 51)
return cards[cardLocation];
else {
throw (new System.ArgumentOutOfRangeException("cardLocation", cardLocation, "cardLocation must be between 0 and 51."));
}
}
public void Shuffle()
{
Card[] tempDeck = new Card[52];
bool[] assigned = new bool[52];
Random sourceGen = new Random();
for (int i = 0; i < 52; i++)
{
int destCard = 0;
bool foundCard = false;
while (foundCard == false)
{
destCard = sourceGen.Next(52);
if (assigned[destCard] == false)
foundCard = true;
}
assigned[destCard] = true;
tempDeck[destCard] = cards[i];
}
tempDeck.CopyTo(cards, 0);
}
}
}
CardClient的代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ConsoleApplication1;
namespace CardClient
{
class CardClient
{
static void Main(string[] args)
{
Deck myDeck = new Deck();
myDeck.Shuffle();
for (int i = 0; i < 52; i++)
{
Card tempCard = myDeck.GetCard(i);
Console.Write(tempCard.ToString());
if (i != 51)
Console.Write(", ");
else
Console.WriteLine();
}
Console.ReadKey();
}
}
}
答案 0 :(得分:3)
你有一个公共变量suit
,但该变量的枚举类型是私有的,所以基本上你声明变量是公共可访问的,但类型不是,这没有意义。
您必须将枚举Suit
声明为公开才能解决此问题。
此外,您必须将类Deck
和Card
声明为public,以便其他命名空间中的CardClient
可以访问它。