I'm developing a WPF game with C# and .NET Framework 4.5.1.
I have this class:
public class Player
{
public Card[4] Hand { get; set; }
}
And I need to set that Player.Hand
can only contain four cards ( Card
is a class that represent a card).
How can I do it? The above code show the exception "matrix size cannot be specified in variable declaration"
. And if I use List<Card>()
, I can set max size.
The size of an array is not part of its type.
You need to create it with that size:
public Card[] Hand {get; set;}
public MyClass()
{
Hand = new Card[4];
}
You could also use a full property and initialize the array to that size.
private Card[] hand = new Card[4];
public Card[] Hand
{
get { return hand; }
//Set if you want!
}
In the property declaration, you should specify only property type, but not the data. The array size can be specified in the moment of array creation.
public class Player
{
public void Initialize()
{
// An example of initialization logic
Hand = new Card[4];
for (int i = 0; i < Hand.Length; i++)
Hand[i] = new Card();
}
public Card[] Hand { get; set; }
}
public class Card
{
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.