简体   繁体   中英

C# static member class with members

I have some classes with a static member:

class BuildingA{
   static BuildableComponent buildableA;
}

class BuildingB{
   static BuildableComponent buildableB;
}

This static member has it's own members:

class BuildableComponent{
    int cost;
}

I would like to be able to manipulate the members of the static via the BuildingA and BuildingB classes, eg A.buildableA.cost and B.buildableB.cost - the way I've described it doesn't quite work, but is there a way to do this?

Fields are private by default in C# - you need to add a public access modifier to it:

class BuildableComponent
{
    public int cost;
}

But, as recommended by @EamonnMcEvoy you can make it a property:

class BuildableComponent
{
    public int Cost { get; private set; }
}

Properties are recommended because you can make the field readable from other classes, without allowing other classes to modify the property (as I have done above by making the setter private). They have other advantages, one being that they can be overridden in derived classes if required.

In C# 6 you can also omit the setter entirely, forcing the value to be set only from the constructor and making the property immutable:

class BuildableComponent
{
    public BuildableComponent(int cost)
    {
        Cost = cost;
    }

    public int Cost { get; }
}

You have an additional problem in that the BuildableComponent fields inside BuildingA and BuildingB are static . This means that they belong to the class, and not an instance to the class (ie each instance of the class shares the same value). This means you need to access it in via the class name rather than an instance of the class:

int cost = BuildingA.buildableA.cost;

In this particular case I would ask yourself whether you want this component to be static. If you are going to create multiple BuildingA instances, do you want them to share the same components? If not, make them non-static.

In c#, members on a class default to private , therefore cost can only be accessed from within an instance of BuildableComponent .

You need to add the public access modifier to your cost field, or better yet, make it a property with a get and set:

class BuildableComponent{
    public int cost;
}

OR

class BuildableComponent{
    public int Cost { get; set; };
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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