类无法识别其他类

时间:2017-04-03 15:00:36

标签: c# methods

我是一名新的C#程序员,我想知道为什么我收到object does not contain a definition of ' methodName ' and no extension method ' methodName ' accepting a first argument of type 'object' could be found错误。我不确定为什么这两个类似乎没有连接。

以下是包含我的方法定义的类:

namespace Simple_Restaurant_Simulation
{
    class ChickenOrder
    {
        public int quantity;
        public int GetQuantity(int ChickenQuantity)
        {
            this.quantity = ChickenQuantity;
            return quantity;
        }

        public void CutUp()
        {
            return;
        }

        public void Cook()
        {
            return;
        }
    }
}

和调用方法:

namespace Simple_Restaurant_Simulation
{
    class Employees
    {
        public dynamic NewRequest(int Quantity, string MenuItem)
        {
            if (MenuItem == "Chicken")
            {
                return new ChickenOrder();
            }

            else
            {
                return new EggOrder();
            }
        }

        public dynamic CopyRequest(dynamic MenuItem)
        {
            /*TODO: 
            if(existing order){
                return existing order;
            }           

            else { return "Whaddaya think I am, a miracle worker?"};

            */
            return null;
        }

        public int Inspect(object Order)
        {
            int InspectResult = 0;

            return InspectResult;
        }

        private string PrepareFood(object Order)
        {

            string PrepareResult = null;

            try
            {
                if (Order is ChickenOrder)
                {
                    for (int i=0; i < this.GetQuantity; i++)
                    {
                        Order.CutUp();
                    }
                    Order.Cook();
                    PrepareResult =  "Chicken order has been cooked";
                }
                                return PrepareResult;

            }
            catch (Exception)
            {
            }
        }
    }
}

感谢您的帮助

1 个答案:

答案 0 :(得分:1)

我不确定您在此处尝试做什么,但PrepareMethod无法编译的原因是它接受objectobject类型明显具有此功能没有CutUp()方法。

您可以使用as运算符尝试将Order对象转换为ChickenOrder

ChickenOrder chickenOrder = Order as ChickenOrder;
if (chickenOrder != null)
{
    for (int i = 0; i< this.GetQuantity; i++)
    {
        chickenOrder.CutUp();
    }
    chickenOrder.Cook();
    PrepareResult =  "Chicken order has been cooked";
}

请注意,只有在运行时传递PrepareFood方法的对象实际上是ChickenOrder时,强制转换才会成功。并且为了能够将ChickenOrder对象传递给接受Order参数的方法,ChickenOrder类应该继承自Order

class ChickenOrder : Order
{
    ...
}

EggOrderChickenOrder都是应该从Order基类继承的特定类型的订单。这也意味着您可以将NewRequest方法的返回类型从dynamic更改为Order,并将您传递给object的其他方法的参数类型更改为OrderContentMethods