调用另一个方法中创建的对象

时间:2016-03-13 01:38:05

标签: c# object methods

我正在尝试引用方法中创建的对象。

这是主要方法。

static void Main(string[] args)
{
    //call all cube base details into existance.
    callCubes();

    //Test Output
    Console.WriteLine("Name: " + blank.name);
    Console.WriteLine("Health: " + blank.health);
    Console.WriteLine("Attack: " + blank.attack);
    Console.WriteLine("");
    Console.ReadKey();
}

这是callCubes方法。

static void callCubes()
{
    cube blank = new cube();
    blank.base_stats(00, "Blank", 0, 0, 0, 0, 0, 0.00); //id, name, atk, def, speed, sp. atk, sp. def, health
    blank.ev_stats(0, 0, 0, 0, 0, 0.00); //atk, def, speed, sp. atk, sp. def, health
    blank.moveSet(00, 00, 00, 00);//move1, move2, move3, move4
}

我无法弄清楚当我在第一行调用callCubes时,为什么在当前上下文中没有定义空白。

修改:https://github.com/Mooseymax/Pocket-Cube/blob/master/source%20cs/Program.cs

2 个答案:

答案 0 :(得分:0)

您不会在您发布的源代码中的任何位置声明一个名为cube1的对象。

您可以修改程序以使callCubes()返回它在本地分配和初始化的多维数据集,并将该返回值分配给Main()范围内的对象:

static void Main(string[] args)
{
    //call all cube base details into existance.
    cube cube1 = callCubes();

    //Test Output
    Console.WriteLine("Name: " + cube1.name);
    Console.WriteLine("Health: " + cube1.health);
    Console.WriteLine("Attack: " + cube1.attack);
    Console.WriteLine("");
    Console.ReadKey();
}

static cube callCubes()
{
    cube blank = new cube();
    blank.base_stats(00, "Blank", 0, 0, 0, 0, 0, 0.00); //id, name, atk, def, speed, sp. atk, sp. def, health
    blank.ev_stats(0, 0, 0, 0, 0, 0.00); //atk, def, speed, sp. atk, sp. def, health
    blank.moveSet(00, 00, 00, 00);//move1, move2, move3, move4

    return blank;
}

请注意,按照惯例,像Cube这样的类名和像CallCubes()这样的方法名应该是PascalCased,而不是camelCased。

答案 1 :(得分:0)

在阅读了你想要一次拥有多个立方体之后,为什么不用测试输出放入方法呢?

static void callCubes()
{
    cube blank = new cube();
    blank.base_stats(00, "Blank", 0, 0, 0, 0, 0, 0.00); //id, name, atk, def, speed, sp. atk, sp. def, health
    blank.ev_stats(0, 0, 0, 0, 0, 0.00); //atk, def, speed, sp. atk, sp. def, health
    blank.moveSet(00, 00, 00, 00);//move1, move2, move3, move4

    //Test Output
    Console.WriteLine("Name: " + blank.name);
    Console.WriteLine("Health: " + blank.health);
    Console.WriteLine("Attack: " + blank.attack);
    Console.WriteLine("");
    Console.ReadKey();
}

你无法同时真正陈述两个立方体的统计数据......