开发者

Is an Extension Method the only way to add a function to an Enum?

开发者 https://www.devze.com 2023-01-21 08:44 出处:网络
I have a Direction Enum: Public Enum Direction Left Right Top Bottom End Enum And Sometimes I need to get the inverse, so it seems nice to write:

I have a Direction Enum:

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()

But I can't put a method on an enum! However, I can add an Extension Method (VS2008+) to it.

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

It works, and "if it ain't broke, don't fix it", but I'd love to know if I'm doi开发者_开发百科ng 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.

Note that in C# the extension method would be defined on a static class, but that is a trivial difference, largely one of nomenclature.


You can make a class that behaves like an enum, in the sense that it has static readonly properties that return an instance of the class that contains that value.

The System.Drawing.Color structure for example works this way (although the internal value is not an enum); it has static properties like Color.Redand Color.White, as well as instance properties and methods.

0

精彩评论

暂无评论...
验证码 换一张
取 消