0

好的,我正在使用 C# 类进行我的实验,其中涉及使用 ref 参数、数组和方法。我在执行此操作时遇到了一些问题,我正在寻求帮助。所以.. 首先,我将问题修改为最简单的部分,以帮助我解释我遇到的问题。这是一段简化的代码:

using System;

public class Repository 
{
    string[] titles;

    static void Main(string[] args)
    {
        string title;

        Console.Write("Title of book: ");
        title = Console.ReadLine();

        getBookInfo(ref title);
    }

    static void getBookInfo(ref string title)
    {
        titles[0] = title;
    }

    static void displayBooks(string[] titles)
    {
        Console.WriteLine("{0}", titles[0]);
    }
}

现在,当您尝试编译代码时,您注意到无法编译,因为错误说“需要对象引用才能访问非静态成员 'Repository.titles'”。问题是 3 种方法的格式必须完全按照作业中的说明发布。现在,如何在保留此模板的同时避免此问题?

其他问题,我将如何在 main 中显示方法 displayBooks 的内容?(由于问题,我还没有走到这一步)。

问候,请帮助!

- - - - - - - - - - - - 谢谢你的帮助 !!!---------

4

3 回答 3

1

对于您的第一个问题,请设为titles静态:

private static string[] titles;
于 2011-09-05T22:50:27.057 回答
1

首先,您不需要使用ref,除非您想title更改Main(). 下面的代码演示了这个概念:

static void Main(string[] args)
{
    string a = "Are you going to try and change this?";
    string b = "Are you going to try and change this?";

    UsesRefParameter(ref a);
    DoesntUseRefParameter(b);
    Console.WriteLine(a); // I changed the value!
    Console.WriteLine(b); // Are you going to try and change this?
}

static void UsesRefParameter(ref string value)
{
    value = "I changed the value!";
}

static void DoesntUseRefParameter(string value)
{
    value = "I changed the value!";
}

需要先创建一个数组,然后才能使用它。因此,这是您已更正的代码:

static string[] titles;

static void Main(string[] args)
{
    string title;
    titles = new string[1]; // We can hold one value.

    Console.Write("Title of book: ");
    title = Console.ReadLine();

    getBookInfo(title);
}

static void getBookInfo(string title)
{
    titles[0] = title;
}

要显示您的书籍,您可以尝试以下方法:

static void displayBooks(string[] titles)
{
    // Go over each value.
    foreach (string title in titles)
    {
        // And write it out.
        Console.WriteLine(title);
    }
}
// In Main()
displayBooks(titles);
于 2011-09-05T22:53:01.430 回答
1

好的,首先您尝试将标题分配给尚未初始化的名为titles 的数组的索引0。本质上,当您尝试为其分配值时,它是一个空数组。

解决这个问题的快速方法是像这样修改你的代码:

private static string[] titles;

    static void Main(string[] args)
    {

        string title;

        Console.Write("Title of book: ");
        title = Console.ReadLine();

        getBookInfo(ref title);
        displayBooks(titles);
    }

    static void getBookInfo(ref string title)
    {
        //titles[0] = title;
        titles = new string[] {title};
    }

    static void displayBooks(string[] titles)
    {
        Console.WriteLine("{0}", titles[0]);
    }

如果你想为这个数组分配更多的书并打印出来,你需要用大小初始化数组。我只会使用一个List<string>可以添加的而不定义初始大小。

要将标题数组设置为大小,只需执行以下操作:static string[] titles = new string[50];

回顾一下这个程序打算做什么,还有更多的逻辑需要添加。例如计数器变量为titles数组中的下一个索引添加标题。

于 2011-09-05T22:53:45.440 回答