简体   繁体   English

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
    {

    }
}

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. 我有许多不同的类,以便我能够通过代码访问MyPlayer类而不将它传递给所有它们我只是创建了一个保存变量的静态类。 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. 我可以使用Main.Units.MyPlayer.Movement访问MyPlayer-> Movement,但是这没有链接到我在静态类中定义的MyPlayer实例。

I want to be able to do MyPlayer->Movement->TurnLeft() for example. 我希望能够以MyPlayer-> Movement-> TurnLeft()为例。 How would I achieve this? 我怎么做到这一点? Thanks for your answers. 谢谢你的回答。

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. 为了在Player类中包含Movement实例,您可以定义私有字段movement和公共属性Movement来访问它。

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类的实例并访问其包含的Movement

Player myPlayer = new Player();
myPlayer.Movement.TurnLeft();

Then MyPlayer should have a reference to a Movement instance. 然后MyPlayer应该有一个Movement实例的引用。

public class MyPlayer : Player
{
    public static Movement movement = new Movement();
    ...
}

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

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