在C#中扩展枚举 [英] Extending Enum in C#

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

问题描述

我不知道我是否可以延长枚举类型在C#来实现我的自定义Enum.GetValues​​(型),并调用它像Enum.GetMyCustomValues​​(类型)

I was wondering whether or not I can extend the Enum type in C# to implement my custom Enum.GetValues(type) and call it like Enum.GetMyCustomValues(type)

我想实现这样的:

public static bool IsFlagSet<T>(this T value, T flag) where T : Enum
{
    return (value & flag) != (T)0;
}

,但它不能做... 任何工作变通我能做什么? 干杯

but it cannot be done... any work arounds I can do? Cheers

推荐答案

扩展的情况下工作,而不是创建静态方法。您可以使用扩展基本枚举公共静态无效MyExtensions(枚举值)。但是,这仍然只是创建枚举实例创建方法。只有这样,才能添加静态方法,如你在谈论外部一类是如果类是部分类。

Extensions work on instances, not for creating static methods. You can extend the base Enum using public static void MyExtensions(this Enum value). But this would still only create methods on Enum instances you create. The only way to add static methods like you're talking about externally for a class is if the class is a partial class.

编辑:做这样的事情,你要我写了下面的

to do something like you want I wrote the following

public static bool IsFlagSet<T>(this Enum value, Enum flag)
{
    if (!typeof(T).IsEnum) throw new ArgumentException();
    if (value == flag) return true;
    return ((int)Enum.Parse(typeof(T), value.ToString()) &
        (int)Enum.Parse(typeof(T), flag.ToString())) != 0;
}

*警告,这种方法需要进行深思熟虑的使用,我希望有一个更好的办法做到这一点更前。

*warning, this method needs to be thought out more prior to use, I'm hoping there is a better way to do it.

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

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