从字符串,INT等枚举 [英] Enum from string, int, etc

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

问题描述

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

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.

我不知道如何实现的其他方式,例如: FromInt(INT) FromString(字符串)等,据我知道,我不能创建 MyEnum.FromInt()(静态)扩展方法。那么什么是可能的办法呢?

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?

推荐答案

我会避免污染int或字符串与枚举扩展方法,而不是一个良好的老式静态辅助类可能是为了。

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);
  }
}

这篇关于从字符串,INT等枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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