类对象数组的构造方法 [英] Constructor for an array of class objects
问题描述
在C#中,您可以输入:
In C#, you can type:
int[] ia = new int[] { 1, 2, 3, 4 };
它将初始化一个长度为4的整数数组,其中包含这些数字.
And it will initialize an array of ints, of Length 4, containing those numbers.
我有一个班级Card,代表一个卡片组中的Card,我希望能够说些类似的话:
I have a class Card, representing a Card in a deck, and I want to be able to say something like:
Card[] ca = new Card[] { "4S", "5C", "AH" };
有一张纸牌,第一张是黑桃4张,然后是5张俱乐部,然后是红桃A.
And have an array of Cards, the first Card being the 4 of Spades, then the 5 of Clubs, then the Ace of Hearts.
我已经可以:
Card c = new Card("4S");
还有一张代表黑桃4的卡片.
And have a Card representing the 4 of Spades.
这种构造函数类型甚至可能吗?如果可能的话,我将如何创建它?
Is this constructor type even possible? If possible, how would I create it?
PS:我知道我可以去:
Card[] ca = Cards.Parse("4S 5C AH");
或者类似的la脚,但我希望我能避免这种情况,并使用更漂亮的语法.
Or something lame like that, but I'm hoping I can avoid that, and use prettier syntax.
现在我已经把所有内容都打完了,我感到有些sheep脚.我现在是那个家伙" ... #Guilty
Now that I've typed this all out, I feel a bit sheepish. I'm "that guy" now... #Guilty
推荐答案
常用方法:
var ca = new Card[] { new Card( "4S" ), new Card( "5C" ), new Card( "AH" ) };
显式投射:
class Card
{
...
public static explicit operator Card( string s )
{
return new Card( s );
}
...
}
var ca = new Card[] { (Card)"4S", (Card)"5C", (Card)"AH" };
隐性转换:
class Card
{
...
public static implicit operator Card( string s )
{
return new Card( s );
}
...
}
var ca = new Card[] { "4S", "5C", "AH" };
现在,这是否好取决于您自己决定.我还要考虑卡片类是否应该使用字符串.枚举可能更好,并且可能节省一些验证和解析.
Now, whether this is nice or not is up to you to decide. I'd also think about if the card class should use strings or not. Enums might be nicer, and it'd potentially save some validation and parsing.
这篇关于类对象数组的构造方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!