【发布时间】:2015-09-24 14:41:17
【问题描述】:
在 C# 中,如何使用用户输入或流来决定使用哪个类?此示例使用Console.Readline(),但实际程序将根据循环中读取的流中的数据来决定使用哪个类。这只是简化了问题的一个例子:
static void Main(string[] args)
{
stock aapl = new stock(); //instantiate a class for Apple Stock
stock fb = new stock(); //instantiate a class for Facebook Stock
Console.WriteLine("Please enter a symbol for Apple or Facebook");
string symbol = Console.ReadLine(); //this should get the class to work on
Console.WriteLine("Please enter yesterdays price for the symbol");
double yestPrice = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("Please enter Todays Price for the symbol");
double currPrice = Convert.ToDouble(Console.ReadLine());
//Assuming aapl was entered, how do I
//set values for the appl member using
//the symbol variable like this:
symbol.YesterdaysPrice = yestPrice;
symbol.CurrentPrice = currPrice;
}
class stock
{
private double yesterdayPrice;
private double currentPrice;
private double dailyGain;
public double YesterdaysPrice
{
get { return yesterdayPrice; }
set { yesterdayPrice = value; }
}
public double CurrentPrice
{
get { return currentPrice; }
set { currentPrice = value; }
}
public double DailyGain
{
get { return currentPrice - yesterdayPrice; }
// No need to ever set directly
}
}
【问题讨论】:
-
if (symbol == "fb") { fb.YesterdaysPrice = yestPrice; fb.CurrentPrice = currPrice; },同样适用于苹果......这是最简单的方法。理想情况下,如果您有多个股票,您可以将它们添加到字典中并通过键查找它们。 -
有 500 个符号,价值远不止两个价格。你的建议基本上会创建一个 1000+ 行 switch 语句
-
不,阅读第二部分,将符号添加到字典中,然后按键查找,仍然是 3 行“if”语句。
-
您是否建议
Dictionary或<string,object>其中 object 是类成员? -
差不多,我建议使用
Dictionary<string, stock>,其中字符串是股票代码,“stock”是该代码的股票实例。