关联附加信息与.NET枚举 [英] Associating Additional Information with .NET Enum

查看:131
本文介绍了关联附加信息与.NET枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题最好用一个例子来说明

My question is best illustrated with an example.

假设我有枚举:

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

欲对应于与该方向上的各方向的单位矢量相关联。例如,我想要的东西,会返回(0,1)北(-1,0)西,等我知道在Java中你可以声明枚举内的方法,可提供该功能。

I want to associate the unit vector corresponding to each direction with that direction. For example I want something that will return (0, 1) for North, (-1, 0) for West, etc. I know in Java you could declare a method inside the enum which could provide that functionality.

我目前的解决方案是有一个静态方法 - 定义枚举类内部 - 返回对应于向量中ArrowDirection通过(该方法使用一个Hashtable来完成查找但是这并不重要)。这似乎是...不洁

My current solution is to have a static method -- inside the class that defines the enum -- that returns a vector corresponding to the passed in ArrowDirection (the method uses a HashTable to accomplish the lookup but that's not really important). This seems... unclean.

问:

有用于存储对应于一个enum附加信息的最佳实践的解决方案在.NET?

推荐答案

有一个很棒的新办法做到这一点在C#3.0。最关键的是这个美丽的事实:枚举可以有扩展方法!所以,这里是你可以做什么:

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;
         }
     }
}

现在,你可以这样做

var unitVector = ArrowDirection.North.UnitVector();



甜!我只发现了这一点,大约一个月前,但它是新的C#3.0的功能一个非常不错的结果。

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~~V另一个例子在我的博客。

这篇关于关联附加信息与.NET枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆