猿问

如何在 c 中优雅地填充异构数组#

我有3个不同的类(1个父类和2个子类),并且我创建了一个异构数组:


Parent[] parentArray =  new Parent[9];

我想按此顺序用 3 个父对象、3 个子 1 对象和 3 个子 2 对象填充此数组。


我想知道是否有比这样做更优雅的方法:


parentArray[0] = new Parent();


parentArray[1] = new Parent();


parentArray[2] = new Parent();


parentArray[3] = new Child1();


parentArray[4] = new Child1();


....


parentArray[9] = new Child2();

谢谢!


侃侃无极
浏览 117回答 3
3回答

森栏

个人我只是认为你应该使用对象初始值设定项。但是,对于纯粹的无聊,您可以使用Linq和通用的工厂方法。// Givenpublic static IEnumerable<T> Factory<T>(int count) where T : Parent, new()&nbsp;&nbsp; &nbsp; &nbsp;=> Enumerable.Range(0, count).Select(x => new T());...// Usagevar array = Factory<Parent>(3)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .Union(Factory<Child1>(3))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .Union(Factory<Child2>(3))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .ToArray();

慕桂英4014372

喜欢这个?var parentArray = new Parent[]{&nbsp; &nbsp; new Parent(),&nbsp; &nbsp; new Parent(),&nbsp; &nbsp; new Parent(),&nbsp; &nbsp; new Child1(),&nbsp; &nbsp; ...};

哔哔one

在此情况下,您希望重复执行一定数量的操作。循环通常用于执行此操作。由于您正在初始化数组,因此循环非常适合,因为它们公开了可用于为数组编制索引的整数。在您的方案中,可以使用三个这样的循环。forParent[] parentArray = new Parent[9];for (int i = 0; i < 3; i++){&nbsp; &nbsp; parentArray[i] = new Parent();}for (int i = 3; i < 6; i++){&nbsp; &nbsp; parentArray[i] = new Child1();}for (int i = 6; i < 9; i++){&nbsp; &nbsp; parentArray[i] = new Child2();}
随时随地看视频慕课网APP
我要回答