gpt4 book ai didi

c# - 无法从C#中的相同类但使用不同方法访问对象属性

转载 作者:行者123 更新时间:2023-12-02 10:56:40 24 4
gpt4 key购买 nike

我无法在同一类的方法ClassOperations()中访问在Program类的Main()方法中创建的student1对象的属性。我不断

error CS0103: The name 'student1' does not exist in the current context


using System;

namespace Trials
{
public class Students
{
public int maths;
public int science;
public int english;
public int secondLang;
public int socialScience;
public string name;

public Students(int[] inputMarks)
{
maths = inputMarks[0];
science = inputMarks[1];
english = inputMarks[2];
secondLang = inputMarks[3];
socialScience = inputMarks[4];
}
}

public class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter your name: ");
string inputName = Console.ReadLine();
int[] marks = new int[5];

Console.WriteLine("Enter the maths marks: ");
marks[0] = int.Parse(Console.ReadLine());

Console.WriteLine("Enter the Science marks: ");
marks[1] = int.Parse(Console.ReadLine());

Console.WriteLine("Enter the English marks: ");
marks[2] = int.Parse(Console.ReadLine());

Console.WriteLine("Enter the Second language marks: ");
marks[3] = int.Parse(Console.ReadLine());

Console.WriteLine("Enter the Social Science marks: ");
marks[4] = int.Parse(Console.ReadLine());

Students student1 = new Students(marks);

student1.name = inputName;
ClassOperations();
}

static void ClassOperations()
{
Console.WriteLine("Enter input :");
int input = int.Parse(Console.ReadLine());

switch (input)
{
case 1:
Console.WriteLine(student1.name);
break;
case 2:
Console.WriteLine(student1.maths);
break;
case 3:
Console.WriteLine(student1.science);
break;
case 4:
Console.WriteLine(student1.english);
break;
case 5:
Console.WriteLine(student1.secondLang);
break;
case 6:
Console.WriteLine(student1.socialScience);
break;
}
}
}
}

最佳答案

该错误告诉您问题所在:在方法(student1)中声明的局部变量(Main)在其他方法(ClassOperations,当前上下文)中无法访问。您有几种选择:

  • (静态)属性
  • (静态)字段
  • 方法参数

  • 在此示例中,“最佳”选项是将 student1变量作为参数传递给 ClassOperations方法:
    static void Main(string[] args) {
    // setup elided
    Students student1 = new Students(marks);
    student1.name = inputName;
    // pass as parameter
    ClassOperations(student1);
    }

    static void ClassOperations(Students student) {
    // access value via new name "student"
    Console.WriteLine(student.name);
    }

    根据您的评论,这是带有字段的替代项的外观:
    static Students student; //static field 
    static void Main(string[] args) {
    // setup elided
    // initialize static field
    student = new Students(marks);
    student.name = inputName;
    ClassOperations();
    }

    static void ClassOperations() {
    // access value via static field "student"
    Console.WriteLine(student.name);
    }

    关于c# - 无法从C#中的相同类但使用不同方法访问对象属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61571916/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com