问题
I am trying to create a few nested classes within my main class.
public class MyPlayer : Player
{
public bool TargetEnemy()
{
return true;
}
public class Movement
{
public uint aInt = 1;
public TurnLeft()
{
}
}
public class ActionBar
{
}
}
I have many different classes so that I would be able to access the MyPlayer class through out the code without passing it to all them I just created a static class that holds the variable for it. I am able to access the MyPlayer->Movement using Main.Units.MyPlayer.Movement but this is not linked to the MyPlayer instance I have defined in the static class.
I want to be able to do MyPlayer->Movement->TurnLeft() for example. How would I achieve this? Thanks for your answers.
回答1:
You might be mistaking the concept of class nesting with class composition. In order to have a Movement
instance within your Player
class, you can define a private field movement
and a public property Movement
to access it.
public class Player
{
public bool TargetEnemy()
{
return true;
}
private Movement movement = new Movement();
public Movement Movement
{
get { return movement; }
set { movement = value; }
}
}
public class Movement
{
public uint aInt = 1;
public TurnLeft()
{
}
}
public class ActionBar
{
}
Then, you may create an instance of your Player
class and access its contained Movement
:
Player myPlayer = new Player();
myPlayer.Movement.TurnLeft();
回答2:
Then MyPlayer
should have a reference to a Movement
instance.
public class MyPlayer : Player
{
public static Movement movement = new Movement();
...
}
来源:https://stackoverflow.com/questions/10676003/c-sharp-nested-classes