【问题标题】:C# get class name from User InputC# 从用户输入中获取类名
【发布时间】: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”是该代码的股票实例。

标签: c# .net oop


【解决方案1】:

下面是一个使用字典来解决这个问题的例子:

    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 并且它们都将匹配相同的股票,默认情况下它区分大小写并会为这些股票创建不同的股票.

如果库存不存在,您可以告诉用户它是无效库存,或者您可以添加库存,因为您拥有执行此操作所需的所有数据。我展示了使用价格属性的内联初始化程序添加新股票的示例。

【讨论】:

    【解决方案2】:

    Ron 建议这样做

            static readonly IDictionary<string, Stock> Stocks = new Dictionary<string, Stock>();
            static void Main(string[] args)
            {
    
                Console.WriteLine("Please enter a symbol for Apple or Facebook");
                var symbol = Console.ReadLine(); //this should get the class to work on
    
                Console.WriteLine("Please enter yesterdays price for the symbol");
                var yestPrice = Convert.ToDouble(Console.ReadLine());
    
                Console.WriteLine("Please enter Todays Price for the symbol");
                var currPrice = Convert.ToDouble(Console.ReadLine());
    
    
                Stock stock;
                if (Stocks.ContainsKey(symbol))
                    stock = Stocks[symbol];
                else
                {
                    stock=new Stock();
                    Stocks[symbol] = stock;
                }
    
    
                stock.YesterdaysPrice = yestPrice;
                stock.CurrentPrice = currPrice;
    
            }
    

    【讨论】:

    • 这个实际上不起作用,因为您正在声明一个名称未知的类。所知道的是保存类名称的变量是symbol。不能让任何一个工作。有什么想法吗?
    • 那么首先,您的原始样本没有多大意义。你有一个变量“symbol”,你正在从控制台读取它作为字符串,然后你试图“symbol.YesterdaysPrice=yestPrice”?我认为这是一个错字。您需要清楚地说明您的要求。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-21
    • 2011-02-10
    • 1970-01-01
    相关资源
    最近更新 更多