简体   繁体   中英

C# simulated polymorphism of static classes?

I have been thinking the design over for a couple days now and I'm asymptotically 100% sure this is a design problem. However, here's my predicament: I essentially want to have a compiler checked and polymorphic static classes. Specifically, I have this:

static class TileSettings
{
    static class TileOne
    {
        public const TileType TYPE = TileType.TileOne;
    }

    static class TileTwo
    {
        public const TileType TYPE = TileType.TileTwo;
    }
}

This seems fine but I would like to have the subclasses to follow a contract (like an interface) that TileOne and TileTwo could follow so that somewhere in code I could do something like the following:

public void function(TileSettings SETTINGS_TO_USE)
{
    someLocalVariable = SETTINGS_TO_USE.TYPE;
}

function(TileOne);
function(TileTwo);

One major problem that sticks out to me though is that one can't pass a static class into a function. What I could do is have a static class with methods that take a TileType and use a switch to return that types value. That seems like it would be highly inefficient, however, if it ends up being called a lot. So, any thoughts? Is there something simple I'm unaware of that would solve this? Thanks in advance for any help.

The solution is to stop using static classes if you desire polymorphism. Your initial hunch that this is a design problem sounds accurate to me. There is no good way to achieve this without some sort of hack that would no doubt be problematic from a maintenance/usability/readability standpoint.

Maybe you need something more like a singleton; you would still have instances underneath but generally refer to only one specific instance.

Yes, the answer is: don't use a static class.

How about this:

class TileSettings
{
    public readonly TileType TYPE;

    public static readonly TileSettings TileOne = new TileSettings(TileType.TileOne);
    public static readonly TileSettings TileTwo = new TileSettings(TileType.TileTwo);

    public TileSettings(TileType type)
    {
         TYPE = type;
    }
}

You can use it like this then:

public void function(TileSettings settings)
{
    someLocalVariable = settings;
}

function(TileSettings.TileOne);
function(TileSettings.TileTwo);

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