Question

I'm in the middle of developing a feature in an application that allows a user to save their preferred font (family, size, underlined, bold, or italic). I should start out by saying that I haven't used enums much in my first few years of developing or binary or inside a constructor for that matter so my knowledge in this area is weak.

As many know, setting up a new font is straightforward.

Font font = new Font("Arial", FontStyle.Bold | FontStyle.Underline);

My question is if there is a clean way of passing into the constructor any one of the combinations of underline, bold or italic which could be none of them, maybe just bold, bold or italic, etc?

Clean to me is not having to have to do something like this.

if(myFont.Bold || myFont.Underline || myFont.Italic)
{
    font = new Font("Arial", FontStyle.Bold | FontStyle.Underline | FontStyle.Italic);
}
else if(myFont.Bold || myFont.Underline)
{
    font = new Font("Arial", FontStyle.Bold | FontStyle.Underline);
}
else if(myFont.Bold || myFont.Italic)
{
    font = new Font("Arial", FontStyle.Bold | FontStyle.Italic);
}

... and so forth

Était-ce utile?

La solution

You could do something like this:

string fontName = "Arial";
FontStyle style = FontStyle.Regular;

if (myFont.Bold)
    style |= FontStyle.Bold;

if (myFont.Underline)
    style |= FontStyle.Underline;

if (myFont.Italic)
    style |= FontStyle.Italic;

Font font = new Font(fontName, style);

Autres conseils

You can't have multiple constructors with the same signature, so this is a non starter, unless you artificially create dummy arguments just to differentiate them.

Instead, you should create different static methods, e.g. static MyClass CreateBoldItalic(), one for each combination you want. These will then instantiate the class with your chosen combinations.

You can do something like this. Use this overload of Font's constructor or whichever is suitable for you.

Font myFont = ...;//get your font
Font font = new Font("Arial", myFont.Size, myFont.Style);
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top