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

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

问题描述

在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?

推荐答案

是的,只是代码基础枚举类型,例如

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

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

下面你可能会最终做一些非常讨厌的东西,使用 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:记住写尽管不尽人意,您可以使用 float double 作为枚举的基础类型,以便您需要一些特殊情况以及无符号的值。

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天全站免登陆