跨方法使用对象

Xes*_*iel 1 c# oop methods

再次编辑:我想我现在就明白了.我需要做的就是使用我希望能够访问的类的当前类冒号?人:学生或人:老师这是对的吗?

我目前正在尝试学习面向对象编程的细节.目前我有一个新的对象,如下所示:

class student
{
    int grade; //0 - 100 as opposed to the characters A, B, C, etc.
    string teacher; //For the teacher of the class the student is in.

}

class teacher
{ 
    int courseAverage;
    string name; 
    //teacher.name would correspond to the teacher in the student class.
}

class Program
{
    student Jim;
    Jim = new student();
    teacher John;
    John = new teacher();
}

static void grades()
{
    Jim.grade = 100;
}

static void teacher()
{
    Jim.teacher = "John Smith";
}

static void average()
{
    int average; //For the sake of simplicity I'll leave the average at an int.
    average = (Jim.grade + Sue.grade + Sally.grade + Robert.grade) / 4;
    /*A loop would be set before the average variable to 
    ensure that only students of John would be counted in this.*/

}

static void teacheraverage()
{
    John.courseAverage = average;//from the average method.
}
Run Code Online (Sandbox Code Playgroud)

编辑:

我想做的是修改另一个类的信息.但是,我想从程序类中的方法中修改Jim学生的信息.一种计算具有给定教师的学生的平均成绩的方法.

另外,我在这些中使用静态的唯一原因是因为这是我设法跨方法访问变量的唯一方法.我尝试使用静态方法跨类使用这些方法但没有成功.还有另一种方法吗?

我想用多种方法使用Jim学生.一个将设置Jim的成绩,另一个将设置老师.我想在这种情况下使用不同的方法,以便我可以了解它是如何完成的.

好吧,看起来我的理解不正确.我将尝试类方法中的方法.

ste*_*e_c 5

既然您正在使用C#,并假设您使用的是.NET 3.5,那么您的类可能会看起来像这样:

public class Student
{
    public int Grade { get; set; }
    public string Teacher { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

Grade和Teacher是自动属性,大致相当于Java中的getter和setter,它们就是方法.C#中的属性本质上是获取和设置类的本地成员的快捷方式.

您对上述类的使用将如下所示:

public class Program
{
    // creates a new Student object with the properties Grade and Teacher set.
    Student s = new Student() { Grade = 100, Teacher = "John Smith" }

    Console.Write(s.Grade); // outputs 100
    Console.Write(s.Teacher); // outputs John Smith
}
Run Code Online (Sandbox Code Playgroud)

这是你在找什么?