четверг, 3 ноября 2011 г.

Howto Use Flags To Create Settings

Using the [Flags] attribute on an enum allows to to perform bitwise operations on it so you can use to have settings for class.

This is especially usefull when a class can have multiple settings applied to it.

The example i'm using here is a Font, which can be Bold, Italic, or Underlined. So you'll notice I setup an enumeration with that special flags attribute.. One other thing you have to do is make the enumeration in powers of 2 (Because if you don't you'll do something like 1 | 2 == 3 which is another property of the Enum) 

I hope this code helps ya guys out!
01using System;
02using System.Collections.Generic;
03using System.Text;
04 
05namespace TestFlags
06{
07    class Program
08    {
09        static void Main(string[] args)
10        {
11            Font font = new Font();
12            font.FontProps = FontProperties.Bold | FontProperties.Italic;
13 
14            Console.WriteLine(font.FontProps);
15            Console.ReadLine();
16        }
17    }
18    [Flags]
19    public enum FontProperties
20    {
21        Bold = 1,
22        Italic = 2,
23        Underlined = 4,
24        None = 8
25    }
26    public class Font
27    {
28        FontProperties fontProps;
29        internal FontProperties FontProps
30        {
31            get return fontProps; }
32            set { fontProps = value; }
33        }
34        public Font()
35        {
36            fontProps = FontProperties.None;
37        }
38    }
39}

Комментариев нет: