枚举扩展方法 [英] Enumeration extension methods

查看:228
本文介绍了枚举扩展方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在VS2008中,是有可能写出这将适用于任何枚举的扩展方法。

In vs2008, is it possible to write an extension methods which would apply to any enumeration.

我知道你可以编写针对具体的枚举扩展方法,但我希望能够用一个单一的扩展方法每个枚举。这可能吗?

I know you can write extension methods against a specific enumeration, but I want to be able to every enumeration using a single extension method. Is this possible?

推荐答案

是的,只是code反对基地枚举类型,例如:

Yes, just code against the base Enum type, e.g.

public static void Something(this Enum e)
{
    // code here
}

的下侧是,你可能会最终做了一些非常讨厌的东西,如发现使用真正的基本类型<一href="http://msdn.microsoft.com/en-us/library/system.enum.getunderlyingtype.aspx"><$c$c>Enum.GetUnderlyingType,铸造和下降不同的分支这取决于枚举的基本类型是的,但你可以找到一些很好的用途(例如,我们有 IsOneOf IsCombinationOf 适用于所有枚举的方法)。

The down-side is you'll probably end up doing some quite nasty stuff like finding the real base type using Enum.GetUnderlyingType, casting, and going down different branches depending on what the base type of the enum is, but you can find some good uses for it (e.g. we have IsOneOf and IsCombinationOf methods that apply to all enums).

PS:记得写的是,虽然不明智,你可以使用浮动的方法时基本类型的枚举所以你需要为这些特殊情况下,以及无符号值。

PS: Remember when writing the method that, although ill advised, you can use float and double as the base types for enums so you'll need some special cases for those as well as unsigned values.

这篇关于枚举扩展方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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