.net 枚举扩展方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/276585/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Enumeration extension methods
提问by Eric Haskins
In vs2008, is it possible to write an extension methods which would apply to any enumeration.
在 vs2008 中,是否可以编写适用于任何枚举的扩展方法。
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?
我知道您可以针对特定的枚举编写扩展方法,但我希望能够使用单个扩展方法进行每个枚举。这可能吗?
回答by Greg Beech
Yes, just code against the base Enumtype, e.g.
是的,只需针对基本Enum类型进行编码,例如
public static void Something(this Enum e)
{
// code here
}
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 IsOneOfand IsCombinationOfmethods that apply to all enums).
不利的一面是,您可能最终会做一些非常讨厌的事情,例如Enum.GetUnderlyingType根据枚举的基本类型使用、强制转换和沿着不同的分支查找真正的基本类型,但是您可以找到一些很好的用途它(例如,我们有IsOneOf,并IsCombinationOf适用于所有枚举的方法)。
PS: Remember when writing the method that, although ill advised, you can use floatand doubleas the base types for enums so you'll need some special cases for those as well as unsigned values.
PS:请记住,在编写方法时,虽然不建议,但您可以使用float和double作为枚举的基本类型,因此您需要一些特殊情况以及无符号值。
回答by Scott Dorman
Yes, you can. The target extenstion type is of type Enum. In C#, this would be done as:
是的你可以。目标扩展类型的类型为Enum。在 C# 中,这将完成为:
public static void EnumExtension(this Enum e)
{
}
or like this in VB:
或者像这样在VB中:
<Extension()> _
Public Sub EnumExtension(ByVal s As Enum)
End Sub
回答by Michael La Voie
FYI Here is a great example of an Enum Extension method that I have been able to use. It implements a case insensitive TryParse() function for enums:
仅供参考,这是我能够使用的枚举扩展方法的一个很好的例子。它为枚举实现了不区分大小写的 TryParse() 函数:
public static class ExtensionMethods
{
public static bool TryParse<T>(this Enum theEnum, string strType,
out T result)
{
string strTypeFixed = strType.Replace(' ', '_');
if (Enum.IsDefined(typeof(T), strTypeFixed))
{
result = (T)Enum.Parse(typeof(T), strTypeFixed, true);
return true;
}
else
{
foreach (string value in Enum.GetNames(typeof(T)))
{
if (value.Equals(strTypeFixed,
StringComparison.OrdinalIgnoreCase))
{
result = (T)Enum.Parse(typeof(T), value);
return true;
}
}
result = default(T);
return false;
}
}
}
You would use it in the following manner:
您可以按以下方式使用它:
public enum TestEnum
{
A,
B,
C
}
public void TestMethod(string StringOfEnum)
{
TestEnum myEnum;
myEnum.TryParse(StringOfEnum, out myEnum);
}
Here are the two sites that I visited to help come up with this code:
以下是我访问过的两个站点以帮助编写此代码:
回答by Adriaan de Beer
Here's another example - also nicer IMHO than having to create and initialize a temp variable.
这是另一个示例 - 恕我直言,这比创建和初始化临时变量更好。
public static class ExtensionMethods
{
public static void ForEach(this Enum enumType, Action<Enum> action)
{
foreach (var type in Enum.GetValues(enumType.GetType()))
{
action((Enum)type);
}
}
}
public enum TestEnum { A,B,C }
public void TestMethod()
{
default(TestEnum).ForEach(Console.WriteLine);
}
回答by Koray Bayram
You can also implement conversion method as follows:
您还可以实现如下转换方法:
public static class Extensions
{
public static ConvertType Convert<ConvertType>(this Enum e)
{
object o = null;
Type type = typeof(ConvertType);
if (type == typeof(int))
{
o = Convert.ToInt32(e);
}
else if (type == typeof(long))
{
o = Convert.ToInt64(e);
}
else if (type == typeof(short))
{
o = Convert.ToInt16(e);
}
else
{
o = Convert.ToString(e);
}
return (ConvertType)o;
}
}
Here is an example usage:
这是一个示例用法:
int a = MyEnum.A.Convert<int>();
回答by Esge
Sometimes there is a need to convert from one enum to another, based on the name or value of the enum. Here is how it can be done nicely with extension methods:
有时需要根据枚举的名称或值从一个枚举转换为另一个枚举。以下是如何使用扩展方法很好地完成它:
enum Enum1 { One = 1, Two = 2, Three = 3 };
enum Enum2 { Due = 2, Uno = 1 };
enum Enum3 { Two, One };
Enum2 e2 = Enum1.One.ConvertByValue<Enum2>();
Enum3 e3 = Enum1.One.ConvertByName<Enum3>();
Enum3 x2 = Enum1.Three.ConvertByValue<Enum3>();
public static class EnumConversionExtensions
{
public static T ConvertByName<T>(this Enum value)
{
return (T)Enum.Parse(typeof(T), Enum.GetName(value.GetType(), value));
}
public static T ConvertByValue<T>(this Enum value)
{
return (T)((dynamic)((int)((object)value)));
}
}
回答by Bronek
Another example of making Enum extension - but this time it returns the input enum type.
进行 Enum 扩展的另一个示例 - 但这次它返回输入的枚举类型。
public static IEnumerable<T> toElementsCollection<T>(this T value) where T : struct, IConvertible
{
if (typeof(T).IsEnum == false) throw new Exception("typeof(T).IsEnum == false");
return Enum.GetValues(typeof(T)).Cast<T>();
}
Example of usage:
用法示例:
public enum TestEnum { A,B,C };
TestEnum.A.toElementsCollection();

