尝试以另一种方法访问临时数组

Trying to access a temporary array in another method

如果这是一个愚蠢的问题,我很抱歉,但作为编码的初学者,我发现很难记住我创建的 limits/bounds 个变量。我试图在下面的 GetLetters() 方法中创建一个临时数组,但我稍后需要在 EstimateGrade() 方法中访问此信息,以便“估计成绩”,根据用户的姓名。

我得到的错误是 “名称 'threeLetters' 在当前上下文中不存在”

有没有一种方法可以在不创建 public 数组的情况下访问 threeLetters 数组。

public int[] GetLetters(String userName)
    {
        //Creating an array that will hold the 3 values that determine grade
        int[] threeLetters = new int[3];

        char firstLetter = userName[0];
        threeLetters[0] = userName[0];
        char thirdLetter = userName[2];
        threeLetters[1] = userName[2];
        char fifthLetter = userName[4];
        threeLetters[2] = userName[4];

        if(userName.Length > 5)
        {
            threeLetters = new int[0];
        }

        return threeLetters;
    }

    public int EstimateGrade(int[] grade)
    {
        int sum = (threeLetters[0] + threeLetters[1] + threeLetters[2]) * 85;
        int result = sum % 101;
        return result;
    }

threeLetters[] 对于 GetLetters() 是本地的,即 threeLetters[]GetLetters() 之外是不可访问的。由于您将 threeLetters[] 作为参数传递给 EstimateGrade() 且别名 grade[],因此请将 threeLetters 更改为 grade。请看下面的代码。

public int EstimateGrade(int[] grade)
{
    int sum = (grade[0] + grade[1] + grade[2]) * 85;
    int result = sum % 101;
    return result;
}

在大多数情况下,您可以通过 {} 大括号推断出任何成员的范围。就 classes 而言,访问修饰符为此添加了另一层。

因此在您的示例中,所有变量都是方法的局部变量,但不仅是它们,{}:

中的所有内容
public int[] GetLetters(String userName)
{    
    int[] threeLetters = new int[3];

    char firstLetter = userName[0];    
    char thirdLetter = userName[2];
    char fifthLetter = userName[4];

    if(userName.Length > 5)
    {
        threeLetters = new int[0];
    }

    return threeLetters;
}

在极少数情况下,您可能需要针对不同情况使用相同名称的变量,因此您可以添加更多块来分隔成员,每个嵌套块都可以访问其父块的成员:

public int[] GetLetters(String userName)
{    
    int[] threeLetters = new int[3];

    // some special block 1
    {
        char firstLetter = userName1[0];    
        threeLetters[0] = firstLetter;
    }

    // some special block 2
    {
        char firstLetter = userName2[0];  
        threeLetters[1] = firstLetter ;             
    }

    if(userName.Length > 5)
    {
        threeLetters = new int[0];
    }

    return threeLetters;
}

在 class 中,默认情况下所有成员都是私有的,并且是 class 的本地成员:

class A
{
    // private by default 
    static string Foo()
    {
        return "This is class A";
    }
}

class B
{
    public void Foo()
    {
        var name = A.Foo(); // error, cannot access, A.Foo must be public
    }
}

如果您想从其他方法访问这些变量,您需要将 threeLetters 定义为 class 的字段(或将其移动到 parent/class 范围):

class A
{
    int[] threeLetters = new int[3];
}

同样适用于嵌套的classes,每个嵌套的class都可以访问其父class的成员:

class A
{
    static string Foo() { return "Class A"; }

    public class B
    {
        public static string Foo() { return A.Foo(); } // no error
    }
}

Console.WriteLine(B.Foo());