【问题标题】:C# - Dynamically Creating ObjectsC# - 动态创建对象
【发布时间】:2018-06-12 13:18:41
【问题描述】:

我得到一个包含 1 和 0 的 nXn 网格,并且如果单元格中有 0,我只能向上或向右移动。我需要找到从左下角到达右上角的所有可能方法。为此,我使用了一个在 (0,0) 处初始化的对象 (Bot),其唯一的行为是查看其右侧和其正上方的单元格;如果它是 0,那么它会在该可用单元格中创建一个新的 Bot。

那么我将如何实现这种创造性行为而不必再次明确地实例化该类?

到目前为止我所拥有的(map 是一个二维数组):

using System;

namespace brancher
{
    public class Bot
    {
        public int row = 0;
        public int col = 0;
        public void startRoutine ()
        {
            if (row != 3 && col != 3) {
                if (Globals.map [row, col + 1] == 0) {
                    // This isn't right
                    Bot a = new Bot (row, col + 1);
                }
                if (Globals.map [row + 1, col] == 0) {
                    // This isn't right
                    Bot b = new Bot (row + 1, col);
                }
            }
                if (row == 3 && col == 3) {
                    Globals.count++;
                }
        }
        public Bot (int x, int y)
        {
            row = x;
            col = y;
            startRoutine ();
        }
    }
}

编辑:这不是家庭作业。这是一个挑战。修正了等号和标题。

【问题讨论】:

  • 为什么您要尝试动态创建类?这解决了什么问题?
  • 这是作业吗?
  • 您要创建类的还是实例(又名对象)?
  • 你到底在问什么?你写的代码有什么“不正确”的地方?
  • “动态创建类”与“实例化这个类”有着截然不同的含义。

标签: c# class object


【解决方案1】:
 public class Bot
{
    public int row = 0;
    public int col = 0;
    public void startRoutine()
    {
        if (row != 3 && col != 3)
        {
            if (Globals.map[row, col + 1] == 0)
            {
                // Simply update the data, no need to create a new class
                this.Move(row, col + 1);
            }
            if (Globals.map[row + 1, col] == 0)
            {
                // Simply update the data, no need to create a new class
                this.Move(row + 1, col);
            }
        }
        if (row == 3 && col == 3)
        {
            Globals.count++;
        }
    }

    private void Move(int x, int y)
    {
        row = x;
        col = y;
        startRoutine();
    }
    public Bot(int x, int y)
    {
        row = x;
        col = y;
        startRoutine();
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-05-25
    • 1970-01-01
    • 1970-01-01
    • 2014-06-03
    • 1970-01-01
    • 1970-01-01
    • 2012-09-07
    • 1970-01-01
    相关资源
    最近更新 更多