自己学习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 :(得分: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 :(得分:1)
if (int.TryParse(...))
BidMethod(entryInt, MIN);
else if (double.TryParse(...))
BidMethod(entryDouble, MIN);
...
...