我是一名新的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)
{
}
}
}
}
感谢您的帮助
答案 0 :(得分:1)
我不确定您在此处尝试做什么,但PrepareMethod
无法编译的原因是它接受object
而object
类型明显具有此功能没有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
{
...
}
EggOrder
和ChickenOrder
都是应该从Order
基类继承的特定类型的订单。这也意味着您可以将NewRequest
方法的返回类型从dynamic
更改为Order
,并将您传递给object
的其他方法的参数类型更改为Order
到ContentMethods
。