2017-03-13 2 views
-1

사용자 입력을 가져온 다음 입력 값을 사용하여 차트를 계산하려고 시도하지만 값을 설정할 때마다 값이 0으로 초기 값으로 재설정됩니다. 메소드 StraightLineDepreciation()이 값을 0으로했을 때만 리턴하는 숫자를 입력하지 않았다는 메시지를 반환하기 때문에 이것을 알 수 있습니다. 초기 값은 무엇입니까. 스위치 루프를 벗어난 후 재설정되는 것처럼 보입니다. 여기 내 프로그램이 있습니다.C# 스위치 케이스를 벗어난 후 재설정 값

ProcessMenuItem(ref menuItem,ref amount,ref years); 
StraightLineDepreciation(ref amount, ref years); 

또는 단순히 래퍼 클래스를 만들어 사용하는 대신 주변의 참조 타입을 통과 : 난 그게 문제라고 생각하기 때문에

static void Main(string[] args) 
    { 
     double amount = 0; 
     int years = 0; 
     char menuItem; 
     Console.WriteLine("This program computes depreciation tables using various methods of depreciation"); 
     menuItem = GetMenuChoice(); 
     while (menuItem != 'Q') 
     { 
      ProcessMenuItem(menuItem,amount,years); 
      menuItem = GetMenuChoice(); 
     }   
     Console.WriteLine("Goodbye!"); 
     Console.ReadLine(); 
    } 



    static void ProcessMenuItem(char menuItem, double amount, int years) 
    { 
     switch (menuItem) 
     { 
      case 'A': 
       ProcessSetValues(ref amount, ref years); 
       Console.WriteLine("{0} {1}", amount, years); 
       break; 
      case 'B': 
       StraightLineDepreciation(amount, years); 
       break; 
      case 'C': 
       break; 
      case 'D': 
       break; 
     } 
    } 
    static void ProcessSetValues(ref double amount, ref int years) 
    { 
     amount = GetPositiveDouble("How much money is to be depreciated?"); 
     years = GetPositiveInteger("Over how many years"); 
     return; 

    } 
    static void StraightLineDepreciation(double amount, int years) 
    { 
     if(amount != 0 && years != 0) 
     { 
      amount = amount/years; 
      Console.WriteLine("Year Depreciation"); 
      Console.WriteLine("---- ---------------"); 
      for (int counter = 0; counter < years; counter++) 
      { 
       Console.WriteLine(" {0,+6}{1}", amount, years); 
      } 
     } 
     else 
     { 
      Console.WriteLine("You have not entered any values for the amount and years."); 
     } 
    } 

답변

2

당신은 당신이 당신의 방법의 모든 항목이 ref을 통과하게 확인 할 수 값 유형

class DepreciationTracker 
{ 
    double amount; 
    int years; 
} 

ProcessMenuItem(DepreciationTracker obj) 
{ 
    //modify obj 
} 
StraightLineDepreciation(DepreciationTracker obj) 
{ 
    //modify obj 
} 

또한 입문서는 Value vs Reference Types에 있습니다.

+0

만약 내가 내 ref의 모든 것을 지우면 작동 할까 –

+0

@JeremyCortez 그렇다면 클래스는 Reference Type이지만 int, double, struct 등과 같은 기본 값 타입을 위해서 당신은'ref '. – Sadique

관련 문제