从另一个类别调用一个值

时间:2017-05-27 17:03:23

标签: c#

我想在StudentApp类中调用Promotion值,这样我就可以在GetTotalScore中总结一下。 这里是代码的简要示例.. 已更新代码。

class Tester
{
    static void Main(string[] args)
    {
        Console.WriteLine("Total score (after 10 marks promotion): " + GetTotalScore(app.Students));
    }

    static double GetTotalScore(List<Student> list)
    {
        if (list.Count == 0)
        {
            return 0;
        }
        else
        {
            List<Student> subList = list.GetRange(1, list.Count - 1);
            double subTotal = GetTotalScore(subList);
            double total = .....[0] + subTotal;
            return total;
        }

    }
}

class StudentApp
{
    public void PromoteScore(List<Student> list)
    {
        double Promotion = 0;
        foreach (Student s in Students)
        {
            if (s.Score + 10 > 100)
            {
                Promotion = 100;
            }
            else 
            {
                Promotion = s.Score + 10;
            }
        }
    }
}

任何帮助都会得到赞赏!

2 个答案:

答案 0 :(得分:1)

选项1

将它设为这样的属性:

class StudentApp
{
    public double Promotion { get; private set; }
    public void PromoteScore(List<Student> list)
    {
        foreach (Student s in Students)
        {
            if (s.Score + 10 > 100)
            {
                Promotion = 100;
            }
            else
            {
                Promotion = s.Score + 10;
            }
        }
    }
}

然后你可以像这样访问它;

var app = new StudentApp();
app.PromoteScore(//students...);
double promotion = app.Promotion;

选项2

或者您可以从以下方法返回促销:

class StudentApp
{
    public double PromoteScore(List<Student> list)
    {
        double promotion = 0;
        foreach (Student s in Students)
        {
            if (s.Score + 10 > 100)
            {
                Promotion = 100;
            }
            else
            {
                Promotion = s.Score + 10;
            }
        }

        return promotion;
    }
}

你会像这样使用它;

var app = new StudentApp();
double promotion = app.PromoteScore(//students...);

答案 1 :(得分:0)

正如UnholySheep在评论中所说,问题在于你的变量是一个局部变量,其范围仅在该方法中。也就是说,只有当程序的范围在该方法中时,它才存在,一旦离开范围,您就无法访问该方法。相反,将其变为公共类级变量。

class StudentApp {

public double Promotion {get; set;} 

//do you coding here

}

然后,如果你想访问它,你可以简单地说StudentApp.Promotion。如果你想知道{get; set;}意思是,这是C#中的一种方法,可以快速创建一个简单的getter和setter,而不必编写一个方法来获取值,并像在Java中那样设置它。