我有一个方向枚举:
Public Enum Direction
Left
Right
Top
Bottom
End Enum
,有时我需要得到的倒数,所以它看上去不错写的:
And Sometimes I need to get the inverse, so it seems nice to write:
SomeDirection.Inverse()
但我不能把方法上枚举!不过,我可以添加一个的扩展方法的(VS2008 +),以它。
But I can't put a method on an enum! However, I can add an Extension Method (VS2008+) to it.
在VB中,扩展方法的必须是内部模块 。我真的不喜欢模块了,我试着写,我可以在一个单独的文件共享(中等)简单的类被插入到其它项目。
In VB, Extension Methods must be inside Modules. I really don't like modules that much, and I'm trying to write a (moderately) simple class that I can share in a single file to be plugged into other projects.
模块只能驻留在文件/命名空间的水平,所以我在文件的底部,现在有一种:
Modules can only reside in the file/namespace level so I have one in the bottom of the file now:
Public Class MyClass
'...'
End Class
Public Module Extensions
<Extension()> _
Public Function Inverse(ByVal dir As Direction) As Direction
'...'
End Function
End Module
它的工作原理,以及如果没坏,就不要修理它,但我很想知道,如果我做错了,并有较少的样板更好的办法。也许在.NET 4?
It works, and "if it ain't broke, don't fix it", but I'd love to know if I'm doing it wrong and there's a better way with less boilerplate. Maybe in .NET 4?
最后,我知道我可以写一个行为像一个枚举的结构,但似乎更加倒退。
Finally, I know I could write a structure that behaves like an enum, but that seems even more backwards.
这确实是加(外观)的方法来枚举的唯一途径。
That is indeed the only way to add (the appearance of) a method to an enum.
请注意,在C#的扩展方法将在静态类中定义,但是这是一个微不足道的差异,这主要是命名之一。
Note that in C# the extension method would be defined on a static class, but that is a trivial difference, largely one of nomenclature.