c# - 从 C# 中的列表访问对象参数

标签 c# grasshopper

我正在创建一个包含许多不同参数的代理对象列表,但我不确定如何使用循环访问我所有对象的特定参数......我正在寻找什么要做的是从我的所有代理处获取所有 Point3d 位置。我该怎么做?

// 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);
    }
}

最佳答案

如果您可以更改 Pos 的访问修饰符:

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

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();

注意:Linq 可从 .Net Framework 3.5 获得

关于c# - 从 C# 中的列表访问对象参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53039352/

相关文章:

c# - 为什么这个简单的 RESTful WCF 服务会因 404 错误而失败?

c# - 如何获取 Windows 应用商店应用程序的本地网络 IP 地址

c# - EndInvoke() 是可选的、某种可选的还是绝对不是可选的?

c# - 如何确保 Task.Factory.StartNew 不会减慢主线程的速度?

c# - 从坐标节点索引

c# - Rhinoscript 将 Python 对象移动到 C#

c# - 在 html 电子邮件中发送 DataTable 的内容,从 DataTable 生成 HTML 的首选方法是什么?

python - 当元素与前一个元素不同时,按整数切片列表

c# - 每行换行而不是每个字符换行?