C#嵌套类 [英] C# Nested classes
问题描述
我正在尝试在主类中创建一些嵌套类.
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
{
}
}
我有许多不同的类,因此我可以通过代码访问MyPlayer类,而无需将其传递给所有这些类,我只是创建了一个静态类来为其保存变量.我可以使用Main.Units.MyPlayer.Movement访问MyPlayer-> Movement,但这未链接到我在静态类中定义的MyPlayer实例.
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.
例如,我希望能够执行MyPlayer-> Movement-> TurnLeft().我将如何实现呢?感谢您的回答.
I want to be able to do MyPlayer->Movement->TurnLeft() for example. How would I achieve this? Thanks for your answers.
推荐答案
您可能会误认为类嵌套和类组合的概念.为了在Player
类中包含一个Movement
实例,可以定义一个私有字段movement
和一个公共属性Movement
来访问它.
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
{
}
然后,您可以创建Player
类的实例并访问其包含的Movement
:
Then, you may create an instance of your Player
class and access its contained Movement
:
Player myPlayer = new Player();
myPlayer.Movement.TurnLeft();
这篇关于C#嵌套类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!