来自字符串、整数等的枚举

发布于 2024-10-12 16:22:22 字数 259 浏览 4 评论 0原文

使用扩展方法,我们可以通过为枚举创建扩展方法 ToInt()ToString() 等来创建将枚举转换为其他数据类型(如 string、int)的方法。

我想知道如何以相反的方式实现,例如 FromInt(int)FromString(string) 等。据我所知,我无法创建 MyEnum.FromInt()(静态)扩展方法。那么,有哪些可能的方法呢?

Using extension method we can create methods to convert an enum to other datatype like string, int by creating extension methods ToInt(), ToString(), etc for the enum.

I wonder how to implement the other way around, e.g. FromInt(int), FromString(string), etc. As far as I know I can't create MyEnum.FromInt() (static) extension method. So what are the possible approaches for this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

み零 2024-10-19 16:22:22

我会避免使用枚举的扩展方法污染 int 或 string,而可能需要一个好的老式静态帮助器类。

public static class EnumHelper
{
   public static T FromInt<T>(int value)
   {
       return (T)value;
   }

  public static T FromString<T>(string value)
  {
     return (T) Enum.Parse(typeof(T),value);
  }
}

I would avoid polluting int or string with extension methods for enums, instead a good old fashioned static helper class might be in order.

public static class EnumHelper
{
   public static T FromInt<T>(int value)
   {
       return (T)value;
   }

  public static T FromString<T>(string value)
  {
     return (T) Enum.Parse(typeof(T),value);
  }
}
荒芜了季节 2024-10-19 16:22:22

您真的需要这些扩展方法吗?

MyEnum fromInt = (MyEnum)someIntValue;
MyEnum fromString = (MyEnum)Enum.Parse(typeof(MyEnum), someStringValue, true);

int intFromEnum = (int)MyEnum.SomeValue;
string stringFromEnum = MyEnum.SomeValue.ToString();

Do you really need those extension methods?

MyEnum fromInt = (MyEnum)someIntValue;
MyEnum fromString = (MyEnum)Enum.Parse(typeof(MyEnum), someStringValue, true);

int intFromEnum = (int)MyEnum.SomeValue;
string stringFromEnum = MyEnum.SomeValue.ToString();
婴鹅 2024-10-19 16:22:22

另一种方式可能是...另一种方式;)使用通用扩展方法扩展 int 和 string,它将采用枚举类型作为类型参数:

public static TEnum ToEnum<TEnum>(this int val)
{
    return (TEnum) System.Enum.ToObject(typeof(TEnum), val);
}

public static TEnum ToEnum<TEnum>(this string val)
{
    return (TEnum) System.Enum.Parse(typeof(TEnum), val);
}

用法:

var redFromInt = 141.ToEnum<System.Drawing.KnownColor>();
var redFromString = "Red".ToEnum<System.Drawing.KnownColor>();

不幸的是没有泛型Enums 的约束,所以我们必须在运行时检查 TEnum 类型;为了简化,我们将验证留给 Enum.ToObjectEnum.Parse 方法。

The other way around would be possibly... the other way around ;) Extend int and string with generic extension methods which will take as type parameter the type of an enum:

public static TEnum ToEnum<TEnum>(this int val)
{
    return (TEnum) System.Enum.ToObject(typeof(TEnum), val);
}

public static TEnum ToEnum<TEnum>(this string val)
{
    return (TEnum) System.Enum.Parse(typeof(TEnum), val);
}

Usage:

var redFromInt = 141.ToEnum<System.Drawing.KnownColor>();
var redFromString = "Red".ToEnum<System.Drawing.KnownColor>();

There is unfortunately no generic constraint for Enums, so we have to check TEnum type during runtime; to simplify we'll leave that verification to Enum.ToObject and Enum.Parse methods.

恰似旧人归 2024-10-19 16:22:22

为什么你想要 FromInt 一个扩展方法而不是仅仅强制转换它?

MyEnum fromInt;
if(Enum.IsDefined(typeof(MyEnum), intvalue))
{
    fromInt = (MyEnum) intvalue;
}
else
{
    //not valid
}

或者,对于字符串,您可以使用 Enum.TryParse

MyEnum fromString;
if (Enum.TryParse<MyEnum>(stringvalue, out fromString))
{
    //succeeded
}
else
{
    //not valid
}

why do you want FromInt an extenstion method versus just casting it?

MyEnum fromInt;
if(Enum.IsDefined(typeof(MyEnum), intvalue))
{
    fromInt = (MyEnum) intvalue;
}
else
{
    //not valid
}

alternatively, for strings, you can use Enum.TryParse

MyEnum fromString;
if (Enum.TryParse<MyEnum>(stringvalue, out fromString))
{
    //succeeded
}
else
{
    //not valid
}
一袭白衣梦中忆 2024-10-19 16:22:22

另一种方法(针对问题的字符串部分):(

/// <summary>
/// Static class for generic parsing of string to enum
/// </summary>
/// <typeparam name="T">Type of the enum to be parsed to</typeparam>
public static class Enum<T>
{
    /// <summary>
    /// Parses the specified value from string to the given Enum type.
    /// </summary>
    /// <param name="value">The value.</param>
    /// <returns></returns>
    public static T Parse(string value)
    {
        //Null check
        if(value == null) throw new ArgumentNullException("value");
        //Empty string check
        value = value.Trim();
        if(value.Length == 0) throw new ArgumentException("Must specify valid information for parsing in the string", "value");
        //Not enum check
        Type t = typeof(T);
        if(!t.IsEnum) throw new ArgumentException("Type provided must be an Enum", "T");

        return (T)Enum.Parse(typeof(T), value);
    }
}

部分灵感来自:http://devlicious.com/blogs/christopher_bennage/archive/2007/09/13/my-new-little-friend-enum-lt-t- gt.aspx)

Another approach (for the string part of your question):

/// <summary>
/// Static class for generic parsing of string to enum
/// </summary>
/// <typeparam name="T">Type of the enum to be parsed to</typeparam>
public static class Enum<T>
{
    /// <summary>
    /// Parses the specified value from string to the given Enum type.
    /// </summary>
    /// <param name="value">The value.</param>
    /// <returns></returns>
    public static T Parse(string value)
    {
        //Null check
        if(value == null) throw new ArgumentNullException("value");
        //Empty string check
        value = value.Trim();
        if(value.Length == 0) throw new ArgumentException("Must specify valid information for parsing in the string", "value");
        //Not enum check
        Type t = typeof(T);
        if(!t.IsEnum) throw new ArgumentException("Type provided must be an Enum", "T");

        return (T)Enum.Parse(typeof(T), value);
    }
}

(Partially inspired by: http://devlicious.com/blogs/christopher_bennage/archive/2007/09/13/my-new-little-friend-enum-lt-t-gt.aspx)

若无相欠,怎会相见 2024-10-19 16:22:22

你可以这样做:

public static class EnumExtensions
{
    public static Enum FromInt32(this Enum obj, Int32 value)
    {
        return (Enum)((Object)(value));
    }

    public static Enum FromString(this Enum obj, String value)
    {
        return (Enum)Enum.Parse(obj.GetType(), value);
    }
}

或者:

public static class Int32Extensions
{
    public static Enum ToEnum(this Int32 obj)
    {
        return (Enum)((Object)(obj));
    }
}

public static class StringExtensions
{
    public static Enum ToEnum(this Enum obj, String value)
    {
        return (Enum)Enum.Parse(obj.GetType(), value);
    }
}

You can do:

public static class EnumExtensions
{
    public static Enum FromInt32(this Enum obj, Int32 value)
    {
        return (Enum)((Object)(value));
    }

    public static Enum FromString(this Enum obj, String value)
    {
        return (Enum)Enum.Parse(obj.GetType(), value);
    }
}

Or:

public static class Int32Extensions
{
    public static Enum ToEnum(this Int32 obj)
    {
        return (Enum)((Object)(obj));
    }
}

public static class StringExtensions
{
    public static Enum ToEnum(this Enum obj, String value)
    {
        return (Enum)Enum.Parse(obj.GetType(), value);
    }
}
ら栖息 2024-10-19 16:22:22

您可以在 int 和 string 上创建扩展方法。

或者在其他静态类上创建静态方法。也许像 EnumHelper.FromInt(int) 之类的东西。

但我想提出一个问题:为什么要转换为字符串或整数?这不是你通常使用可枚举的方式,除了序列化。但这应该由某种基础设施来处理,而不是您自己的代码。

You can either make extension methods on int and string.

Or make static method on some other static class. Maybe something like EnumHelper.FromInt(int).

But I would pose one question : Why do you want to convert to string or int? Its not how you normaly work with enumerables, except maybe serialisation. But that should be handled by some kind of infrastructure, not your own code.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文