将附加信息与.NET枚举相关联 [英] Associating Additional Information with .NET Enum
问题描述
假设我有枚举:
public enum ArrowDirection
{
北,
南,
东,
西
}
我想将与每个方向相对应的单位向量与该方向相关联。例如,我想要的东西将返回(0,1)为North,(-1,0)为西等。我知道在Java中,你可以声明一个方法在枚举内可以提供这个功能。
我目前的解决方案是在定义枚举的类中有一个静态方法 - 返回与ArrowDirection中传递的向量相对应的向量(该方法使用HashTable来完成查找但这并不重要)。这个似乎是不洁净的。
问题:
是否有一个最佳实践解决方案来存储对应于枚举的附加信息.NET?
在C#3.0中有一种FANTASTIC新方法。关键是这个美丽的事实:枚举可以有扩展方法!所以,你可以这样做:
public enum ArrowDirection
{
North,
南,
东,
西
}
public static class ArrowDirectionExtensions
{
public static UnitVector UnitVector(this ArrowDirection self)
{
//将此替换为字典或任何你想要的...你得到的想法
switch(self)
{
case ArrowDirection.North:
返回新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);
默认值:
返回null;
}
}
}
现在,你可以这样做:
var unitVector = ArrowDirection.North.UnitVector();
甜蜜!大约一个月前我才发现这一点,但这是新的C#3.0功能的一个非常好的结果。
My question is best illustrated with an example.
Suppose I have the enum:
public enum ArrowDirection
{
North,
South,
East,
West
}
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.
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.
Question:
Is there a best-practice solution for storing additional information corresponding to an enum in .NET?
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.
这篇关于将附加信息与.NET枚举相关联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!