简体   繁体   English

如何从非父类调用抽象类

[英]How to call abstract class from non parent

I have a non abstract class called 'Player', and an abstract class called 'Score' with a subclass of 'Combination'. 我有一个名为“ Player”的非抽象类,还有一个名为“ Score”的抽象类,其子类为“ Combination”。 Within Combination there is and abstract method used in further subclasses. 在Combination中,还有用于其他子类的abstract方法。

How can I call my abstract method from the non-parent method 'Player' without making them static? 我如何从非父方法“ Player”中调用我的抽象方法而又不使其变为静态?

// This is the abstract method within Combination, 
// it uses the face values from rolled dice to calculate the score.

abstract public int CalculateScore(int[] faceValues);

//Array of 'Score's in Player

private Score[] scores = new Score[10];

You cannot. 你不能。 This is access modifier and it was designed to narrow access to a class. 这是访问修饰符,旨在缩小对类的访问。 To use it in your case, I suggest to change accessibility from abstract to public of a Score class. 要在您的情况下使用它,建议将Score类的可访问性从abstract更改为public

If I understand you correctly, you want to implement CalculateScore in your derived class by accessing the scores field? 如果我理解正确,您是否想通过访问scores字段在派生类中实现CalculateScore

Simple answer is, you can't as you designed it that way. 简单的答案是,您不能按照这种方式设计。 private modifier makes sure, only your own class can access the field. private修饰符确保只有您自己的类可以访问该字段。 If you want derived classes to have access to that field, you have to change your modifier to protected on the scores -field. 如果您希望派生类可以访问该字段,则必须将您的修饰符更改为scores -field上的protected

If you do not want your derived classes to have access to scores directly, you have to implement methods with at least protected access, that modify the scores -field in a defined way, on the base class. 如果您不希望派生类直接访问scores ,则必须实现至少具有protected访问权的方法,这些方法必须在基类上以定义的方式修改scores -field。

So your situation: 所以你的情况:

  • Player is a normal classs Player是普通班
  • Score is an abstract class Score是一个抽象类
  • Combination is an abstract class too that subclasses Score . Combination也是一个抽象类,它是Score子类。 It contains an abstract method CalculateScore that you want to call from inside the Player class. 它包含您要从Player类内部调用的抽象方法CalculateScore
  • Player has an array of Score s Player具有一个Score数组

You can check if an element in your Score array is of type Combination then cast it. 您可以检查Score数组中的元素是否为Combination类型,然后进行转换。

if(score[0] is Combination)
{
    (score[0] as Combination).CalculateScore(/* arguments here */);
}

You might need to rethink how your classes work though. 但是,您可能需要重新考虑您的课程是如何工作的。 IMHO, Player shouldn't be the one calculating the scores. 恕我直言,玩家不应该是计算得分的人。 Maybe use a ScoreCalculatorService to handle that. 也许使用ScoreCalculatorService来处理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM