Associating Additional Information with .NET Enum

后端 未结 5 1253
轻奢々
轻奢々 2021-02-01 04:51

My question is best illustrated with an example.

Suppose I have the enum:

public enum ArrowDirection
{
    North,
    South,
    East,
    West
}
         


        
5条回答
  •  时光取名叫无心
    2021-02-01 05:50

    There's a FANTASTIC new way to do this in C# 3.0. The key is this beautiful fact: Enums can have extension methods! So, here's what you can do:

    public enum ArrowDirection
    {
        North,
        South,
        East,
        West
    }
    
    public static class ArrowDirectionExtensions
    {
         public static UnitVector UnitVector(this ArrowDirection self)
         {
             // Replace this with a dictionary or whatever you want ... you get the idea
             switch(self)
             {
                 case ArrowDirection.North:
                     return new UnitVector(0, 1);
                 case ArrowDirection.South:
                     return new UnitVector(0, -1);
                 case ArrowDirection.East:
                     return new UnitVector(1, 0);
                 case ArrowDirection.West:
                     return new UnitVector(-1, 0);
                 default:
                     return null;
             }
         }
    }
    

    Now, you can do this:

    var unitVector = ArrowDirection.North.UnitVector();
    

    Sweet! I only found this out about a month ago, but it is a very nice consequence of the new C# 3.0 features.

    Here's another example on my blog.

提交回复
热议问题