是一个扩展方法将函数添加到一个枚举的唯一途径? [英] Is an Extension Method the only way to add a function to an Enum?

查看:214
本文介绍了是一个扩展方法将函数添加到一个枚举的唯一途径?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个方向枚举:

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.

这篇关于是一个扩展方法将函数添加到一个枚举的唯一途径?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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