samedi 28 mars 2020

C# design - How can I essentially group classes and enums in a list without an empty interface?

I am designing a text renderer. I am building the logic of how to split a string into lines to fit within the textbox. The way I would like to do this is by first splitting the full string into "Words", "Spaces" and "Newlines", then building an algorithm to measure how much can fit on one line before moving onto the next.

However, "Word" needs to be a class/struct because it wants to hold extra attributes such as "FontStyle", "Colour", etc. "Space" and "NewLine" are just markers - they don't need any data.

At the moment I have the following framework:

interface ILineComponent
{
}

struct Word : ILineComponent
{
    public string Text;
    public FontStyle Style;
    public Colour Colour;

    public Word(string text, FontStyle style, Colour colour)
    {
        Text = text;
        Style = style;
        Colour = colour;
    }
}

struct Space : ILineComponent
{
}

struct NewLine : ILineComponent
{
}

struct Line
{
    public List<ILineComponent> Segments;

    public Line(List<ILineComponent> segments)
    {
        Segments = segments;
    }
}

The idea then being I will go through the Line and measure how many (word,space,...,word,space) will fit on a line (or word,...,newline) before breaking it up to another line. At the moment this will utilise logic like:

foreach (ILineComponent component in line)
{
    if (component is Word)
    //..
    else if (component is Space)
    //...
    else if (component is NewLine)
    //...
}

But this design breaches CA1040.

How could I design this better?

Aucun commentaire:

Enregistrer un commentaire