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
}
}
다음은이 문제를 해결하기 위해 사전을 사용하는 예입니다.
static void Main(string[] args)
{
Dictionary<string, stock> stocks = new Dictionary<string, stock>(StringComparer.CurrentCultureIgnoreCase);
//Add the initial stocks here if desired.
Console.WriteLine("Please enter a symbol");
string symbol = Console.ReadLine();
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());
if (stocks.ContainsKey(symbol)) //The dictionary contains the stock
{
stocks[symbol].YesterdaysPrice = yestPrice;
stocks[symbol].CurrentPrice = currPrice;
}
else
{
//The stock wasn't found, we can either say invalid stock, or add one like this:
stocks[symbol] = new stock()
{
YesterdaysPrice = yestPrice,
CurrentPrice = currPrice;
};
}
}
사전은 맨 위에 선언되고 입력 된 모든 기호를 보유합니다. 사용자가 기호와 데이터를 입력하면 if
문은 해당 기호가있는 주식이 이미 존재하는지 확인하고 존재하는 경우 해당 값을 업데이트합니다. 간단히 StringComparer.CurrentCultureIgnoreCase
말씀 드리면, 사용자가 AAPL 또는 aapl 또는 aApL을 입력 할 수 있도록 인수를 사용하여 사전을 만들었으며 모두 동일한 주식과 일치하며 기본적으로 대소 문자를 구분하며 다른 주식을 만듭니다.
주식이 존재하지 않는 경우 사용자에게 유효하지 않은 주식임을 알리거나 필요한 모든 데이터가 있으므로 주식을 추가 할 수 있습니다. 가격 속성에 대한 인라인 이니셜 라이저를 사용하여 새 주식을 추가하는 예를 보여주었습니다.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다