[英]Can't call method inside of a inherited class from Main
I have created a basic template program helping me understand Interfaces, classes and the such. 我创建了一个基本的模板程序,可以帮助我理解接口,类等。
What I am trying to achieve is simply calling a method that resides in an inherited class hierarchy. 我试图实现的目标只是调用驻留在继承的类层次结构中的方法。
I am getting this error: 我收到此错误:
'Book' does not contain a definition for 'BulkOrder' and no extension method for 'BulkOrder' accepting a first argument of type 'Book' could be found(are you missing a using directive or an assembly reference?)
'Book'不包含'BulkOrder'的定义,也找不到'BulkOrder'的扩展方法,该扩展方法接受类型为'Book'的第一个参数(是否缺少using指令或程序集引用?)
This is the main program 这是主程序
Main
{
BulkBook book2 = new BulkBook(FILLER);
BulkOrder(book2);
}
public static void BulkOrder(Book book2)
{
Console.WriteLine(Filler text);
book2.BulkOrder(); <------- belongs in inherited class
}
This is the inherited class structure 这是继承的类结构
abstract class Publication
various code
class Book : Publication
various code
class BulkBook : Book
various code
public void BulkOrder() <------ method
{
Copies = Copies + BATCH_SIZE;
}
class BulkBook : Book
...
public void BulkOrder()
{
Copies = Copies + BATCH_SIZE;
}
The BulkOrder
method only exists in the BulkBook
class, not the Book
class. BulkOrder
方法仅存在于BulkBook
类中,而不存在于Book
类中。
Since BulkOrder
exists in BulkBook
and not Book
you need to cast book2
to BulkBook
: 由于
BulkOrder
存在于BulkBook
而不是Book
您需要将book2
BulkBook
为BulkBook
:
((BulkBook)book2).BulkOrder();
However you may wish to verify that book2
is in fact a BulkBook
: 但是,您可能希望验证
book2
实际上是BulkBook
:
if (book2 is BulkBook)
{
((BulkBook)book2).BulkOrder();
}
An alternative solution would be to have the method accept the type BulkBook
rather than Book
: 一种替代解决方案是让该方法接受
BulkBook
类型而不是Book
类型:
public static void BulkOrder(BulkBook book2)
{
Console.WriteLine(Filler text);
book2.BulkOrder(); //This should now work
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.