2017-05-27 131 views
0

我想调用类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; 
      } 
     } 
    } 
} 

任何帮助被赞赏!

+0

你不能,该变量对于'PromoteScore'方法是局部的。您需要从方法中返回它,或者以其他方式使其可访问(例如:一个'公共'成员变量或属性) – UnholySheep

回答

0

As UnholySheep在评论中说,这里的问题在于你的变量是一个局部变量,其范围只在该方法中。也就是说,它只存在于该方法的范围内,一旦你离开范围,你就无法访问该方法。相反,把它变成一个公共类级变量。

class StudentApp { 

public double Promotion {get; set;} 

//do you coding here 

} 

那么如果你想访问它,你可以简单地说StudentApp.Promotion。如果你想知道{get;这意味着,这是C#中的一种方法,可以快速创建一个简单的getter和setter,而不必写出一个方法来获取值,并按照您在Java中的设置。

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...); 
+0

在GetTotalScore上调用它时有条件... – Pump1020

+0

您有什么问题?在GetTotalScore类的类中是否有'StudentApp'的实例? – CodingYoshi

+0

基本上,我不知道如何实现...你的var app = new StudentApp(); app.PromoteScore(//学生...); 双促销= app.Promotion; – Pump1020