简体   繁体   中英

Dynamically create objects based on a runtime count value - C#

Simple example of scenario I am trying to implement

class ATest
{
    int a;
    int b;
    BTest[];
}

class BTest
{
    int X;
    int Y;
}
  • I need to create ATest and BTest dynamically based on a value.
  • I tried it as Atest[] aobj = new Atest[count]; (This count value will be set programmatically)
  • Now I need to create Array of Objects of B dynamically and assign it to A
  • Currently I assume static value for count and assigned it

     Atest[] aobj = new Atest[20]; BTest[] bobj = new BTest[1]; bobj[0] = new Btest(); aobj[0] = new ATest(); aobj[0].BTest = bobj; BTest[] bobj1 = new BTest[1]; bobj1[0] = new Btest(); aobj1[0].BTest = bobj1; 

This may not be the best way to code.

Please suggest on dynamically implementing it - Dynamically create number of BTest object arrays and assign it for ATest instances

Try using constructors:

class ATest {
    int a;
    int b;
    BTest[] btests;
    public ATest(int numOfB) {
        btests = new BTest[numOfB];
    }
}

The you can create and initialize your atests in a simple loop:

int M = 20; // Number of Test A objects
int N = 10; // Number of Test B objects per Test A
var atests = new ATest[M];
for (var i = 0 ; i != M ; i++) {
    atests[i] = new ATest(N);
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM