2014-03-05 1 views
-1

C#을 배우는 것은 숙제가 아닙니다. 프로그램은 3 가지 오버로드 된 메소드를 모두 호출합니다. 사용자의 입력 유형 (int, double 또는 string)에 따라 하나의 메소드 만 호출해야합니다. 어떻게해야합니까? 메소드에 if 문을 사용합니까? 기본/간단한 답변하시기 바랍니다. 고맙습니다!!오버로드 된 메서드가 너무 많습니다. 하나만 필요합니다.

static void Main(string[] args) 
    { 
     int entryInt; 
     double entryDouble; 
     string entryString; 
     string userEntry; 

     const double MIN = 10.00; 

     Console.WriteLine("\t** WELCOME TO THE AUCTION! **\n"); 
     Console.Write("Please enter a bid for the item: "); 
     userEntry = Console.ReadLine(); 

     int.TryParse(userEntry, out entryInt); 
     double.TryParse(userEntry, out entryDouble); 
     entryString = userEntry.ToLower(); 

     BidMethod(entryInt, MIN); 
     BidMethod(entryDouble, MIN); 
     BidMethod(entryString, MIN); 

     Console.ReadLine(); 
    } 

    private static void BidMethod(int bid, double MIN) 
    { // OVERLOADED - ACCEPTS BID AS AN INT 
     Console.WriteLine("Bid is an int."); 
     Console.WriteLine("Your bid is: {0:C}", bid); 
     if (bid >= MIN) 
      Console.WriteLine("Your bid is over the minimum {0} bid amount.", MIN); 
     else 
      Console.WriteLine("Your bid is not over the minimum {0} bid amount.", MIN); 
    } 

    private static void BidMethod(double bid, double MIN) 
    { // OVERLOADED - ACCEPTS BID AS A DOUBLE 

     Console.WriteLine("Bid is a double."); 
     Console.WriteLine("Your bid is: {0:C}", bid); 
     if (bid >= MIN) 
      Console.WriteLine("Your bid is over the minimum {0} bid amount.", MIN); 
     else 
      Console.WriteLine("Your bid is not over the minimum {0} bid amount.", MIN); 
    } 

    private static void BidMethod(string bid, double MIN) 
    { // OVERLOADED - ACCEPTS BID AS A STRING 

     string amount; 
     int amountInt; 

     if (bid.StartsWith("$")) 
      amount = (bid as string).Trim('$'); // Remove the $ 
     if (bid.EndsWith("dollar")) 
      amount = bid.TrimEnd(' ', 'd', 'o', 'l', 'l', 'a', 'r', 's'); 
     else 
      amount = bid; 

     Int32.TryParse(amount, out amountInt); // Convert to Int 
     Console.WriteLine("Bid is a string."); 

     Console.WriteLine("Your bid is: {0:C}", bid); 
     if (amountInt >= MIN) 
      Console.WriteLine("Your bid is over the minimum {0} bid amount.", MIN); 
     else 
      Console.WriteLine("Your bid is not over the minimum {0} bid amount.", MIN); 
    } 
} 

}

+0

메소드 중 하나만 호출하려면 메소드 중 하나만 호출하도록 코드를 작성해야합니다. if 문을 사용하십시오. – SLaks

답변

2

여기에 디자인은 어쨌든 좋은,하지만하지 않습니다. TryParse 메서드는 문자열을 구문 분석했는지 여부를 나타내는 부울 값을 반환합니다. 이를 사용하여 호출 할 메소드를 결정할 수 있습니다.

if (int.TryParse(userEntry, out entryInt)) 
{ 
    BidMethod(entryInt, MIN); 
} 
else if (double.TryParse(userEntry, out entryDouble)) 
{ 
    BidMethod(entryDouble, MIN); 
} 
else 
{   
    entryString = userEntry.ToLower(); 
    BidMethod(entryString, MIN); 
} 
1
if (int.TryParse(...)) 
    BidMethod(entryInt, MIN); 
else if (double.TryParse(...)) 
    BidMethod(entryDouble, MIN); 
... 
...