2017-05-27 122 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