首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从C#中的列表中访问对象参数

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

Stack Overflow用户
提问于 2018-10-29 05:38:58
回答 3查看 1.5K关注 0票数 1

我正在创建一个代理对象列表,这些对象包含许多不同的参数,但我不知道如何使用loop...what访问所有对象的特定参数,我想要做的是从所有代理中获取所有的Point3d位置。我该怎么做?

代码语言:javascript
复制
// 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);
    }
}
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2018-10-29 05:55:51

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

代码语言:javascript
复制
class Agent
{
    public Point3d Pos = new Point3d();
    //.
    //.
    //.
}

代码语言:javascript
复制
class Agent
{
    public Agent()
    {
       Pos = new Point3d();
    }
    public Point3d Pos { get;private set; }
    //.
    //.
    //.
}
代码语言:javascript
复制
List<Agent> allAgents = new List<Agent>();
List<Point3d> agentPositions = new List<Point3d>();

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


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

注意: Linq可从.Net Framework3.5获得

票数 2
EN

Stack Overflow用户

发布于 2018-10-29 06:07:13

代码语言:javascript
复制
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
}
票数 2
EN

Stack Overflow用户

发布于 2018-10-29 07:40:52

您无法访问Point3d Pos,因为默认情况下它是私有的。因此,请像下面这样使用公共访问修饰符,并希望它能够解决这个问题:

代码语言:javascript
复制
public Point3d Pos = new Point3d();
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53039352

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档