简体   繁体   中英

Access object parameters from a List in C#

I'm creating a list of agent objects that hold a number of different parameters but I'm unsure of how to access particular parameter(s) of all of my objects using a loop...what I'm looking to do is get all of the Point3d positions from all of my agents. How would I do this?

// Define Agent class
class Agent
{
    Point3d Pos = new Point3d();
    Vector3d Vec = new Vector3d();
    int Alignment;
    double Separation;
    double Cohesion;
    double NeighborRadius;

    public Agent(Point3d pos, Vector3d vec, int alignment, double separation, double cohesion, double neighborRadius)
    {
        Pos = pos;
        Vec = vec;
        Alignment = alignment;
        Separation = separation;
        Cohesion = cohesion;
        NeighborRadius = neighborRadius;
    }
}

protected override void SolveInstance(IGH_DataAccess DA)
{
    // Initialize Agents
    for (int i = 0; i < agents; i++)
    {
        double xPos = RandomfromDouble(0.0, boundx);
        double yPos = RandomfromDouble(0.0, boundy);
        double zPos = RandomfromDouble(0.0, boundz);

        Point3d pos = new Point3d(xPos, yPos, zPos);        // Create Agent Start Position
        Vector3d vec = new Vector3d(xPos + 1, yPos, zPos);  // Create Agent Start Vector

        Agent agent = new Agent(pos, vec, alignment, separation, cohesion, neighborRadius);
        allAgents.Add(agent);
        agentPositions.Add(pos);
    }
}

if you can change access modifier for Pos:

class Agent
{
    public Point3d Pos = new Point3d();
    //.
    //.
    //.
}

or

class Agent
{
    public Agent()
    {
       Pos = new Point3d();
    }
    public Point3d Pos { get;private set; }
    //.
    //.
    //.
}

List<Agent> allAgents = new List<Agent>();
List<Point3d> agentPositions = new List<Point3d>();

// Initialize Agents
//.
//.
//.


agentPositions = allAgents
            .Select(agent => agent.Pos)
            .ToList();

note: Linq is available from .Net Framework 3.5

class Agent
{
    public Point3d Pos {get; private set;}
    public Agent() 
    {
        Pos = new Point3d();
    }
    ....
}
foreach (Agent ag in allAgents)
{
    Console.WriteLine(ag.Pos); //might need to dereference a specific member like x,y, or z
}

You are unable to access Point3d Pos because by default it is private. So use public access modifier like below and hope it will fix the issue:

public Point3d Pos = new Point3d();

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