【问题标题】:Get int value from enum in C#从 C# 中的枚举中获取 int 值
【发布时间】:2010-10-30 21:55:38
【问题描述】:

我有一个名为Questions(复数)的课程。在这个类中有一个名为Question(单数)的枚举,看起来像这样。

public enum Question
{
    Role = 2,
    ProjectFunding = 3,
    TotalEmployee = 4,
    NumberOfServers = 5,
    TopBusinessConcern = 6
}

Questions 类中,我有一个get(int foo) 函数,它为foo 返回一个Questions 对象。有没有一种简单的方法可以从枚举中获取整数值,以便我可以执行类似 Questions.Get(Question.Role) 的操作?

【问题讨论】:

  • 我知道我迟到了,但是不要将你的方法定义为get(int foo),你可以将它定义为get(Question foo),然后在方法中进行转换,你可以调用你的方法作为Questions.Get(Question.Role)
  • 试试这个:int int_Choose = (int) Question.Role;

标签: c# enums casting int


【解决方案1】:

只需投射枚举,例如

int something = (int) Question.Role;

以上内容适用于您在野外看到的绝大多数枚举,因为枚举的默认基础类型是int

然而,正如cecilphillip 指出的那样,枚举可以有不同的底层类型。 如果枚举声明为uintlongulong,则应将其强制转换为枚举的类型;例如对于

enum StarsInMilkyWay:long {Sun = 1, V645Centauri = 2 .. Wolf424B = 2147483649};

你应该使用

long something = (long)StarsInMilkyWay.Wolf424B;

【讨论】:

  • @Harry 这不是真的。您可以在不强制转换的情况下创建枚举,这不是必需的。而且我只在特殊情况下分配数字,大多数时候,我将其保留为默认值。但你可以做enum Test { Item = 1 } 并看到1 == (int)Test.Item 是相等的。
  • @Jaider (int)Test.Item 那是演员表! () 是显式转换运算符。
  • @Sinthia V 他说你可以创建它而不用强制转换,这是正确的
  • 如果enum Question 的基础类型不是int 而是long,此转换将截断Roles 整数值!
  • 当您接受Enum 作为参数时,您知道您只能获得固定数量的可能整数值。另一方面,如果您只采用int,那么您必须验证int 是否在可接受的值范围内,从而使代码复杂化。你总是可以覆盖你的签名,比如 ``` public void MyMethod(int x) { // do something with x } public void MyMethod(Enum x) { this.MyMethod((int) x); } ````
【解决方案2】:

由于枚举可以是任何整数类型(byteintshort 等),获取枚举的基础整数值的更可靠的方法是使用 GetTypeCode方法结合Convert 类:

enum Sides {
    Left, Right, Top, Bottom
}
Sides side = Sides.Bottom;

object val = Convert.ChangeType(side, side.GetTypeCode());
Console.WriteLine(val);

无论底层的整数类型如何,这都应该有效。

【讨论】:

  • 在处理 T:enum 的泛型类型(实际上是 T:struct、IConvertible 但那是另一回事)时,这项技术证明了它的价值。
  • 你将如何修改它以打印出侧的十六进制值?此示例显示十进制值。问题是var 的类型是object,所以你需要拆箱它会变得比我想要的更乱。
  • 如果你想转换成 int 试试(如果是枚举 Sides : int) [...] object val = Convert.ChangeType(side, typeof(int)); [...]
  • @TimAbell 我只能说,我们发现动态编译的 aspx 页面(您必须在其中将 .cs 文件部署到实时服务器)为每个值分配不同的整数。这意味着在一台机器上序列化的对象,在不同的机器上使用不同的值反序列化并有效地被破坏(导致小时的混乱)。我们向 MS 提出了这个问题,我似乎记得他们说过,在跨不同框架版本构建时,不能保证自动生成的整数是相同的。
  • @TimAbell 在另一个场合,开发人员删除了一个过时/未使用的 Enum 值,导致序列中的所有其他值减一。因此,我们的编码标准现在要求始终明确指定 ID,否则添加/删除甚至自动格式化代码(例如按字母顺序排序)将更改所有导致数据损坏的值。我强烈建议任何人明确指定所有 Enum 整数。如果它们与外部(数据库)存储的值相关,这一点非常重要。
【解决方案3】:

将其声明为具有公共常量的静态类:

public static class Question
{
    public const int Role = 2;
    public const int ProjectFunding = 3;
    public const int TotalEmployee = 4;
    public const int NumberOfServers = 5;
    public const int TopBusinessConcern = 6;
}

然后您可以将其引用为 Question.Role,它的计算结果始终为 int 或您定义的任何值。

【讨论】:

  • 我会使用static readonly int,因为常量被编译成它们的硬值。见stackoverflow.com/a/755693/492
  • 这个解决方案实际上并没有提供强类型枚举的真正好处。例如,如果我只想将 GameState-enum-parameter 传递给特定方法,编译器不应允许我将任何 int 变量作为参数传递。
  • @CADBloke 这正是您使用const 而不是static readonly 的原因,因为每次比较static readonly 时,您都在进行方法调用以获取变量的值,而使用const 您正在直接比较两种值类型。
  • @brettof86 是的,一个 const 会更快,如果编译限制永远不会成为问题,那么一切都很好。
  • @Zack 我没有很好地解释这一点,compilation limitation 我的意思是该值在编译时是硬编码的,因此对该值的任何更改都需要 all 使用它的程序集需要重新编译。我倾向于同意你的用法,因为改变价值观会产生深远的影响。
【解决方案4】:

在相关说明中,如果您想从 System.Enum 获取 int 值,则在此处给出 e

Enum e = Question.Role;

你可以使用:

int i = Convert.ToInt32(e);
int i = (int)(object)e;
int i = (int)Enum.Parse(e.GetType(), e.ToString());
int i = (int)Enum.ToObject(e.GetType(), e);

最后两个很丑。我更喜欢第一个。

【讨论】:

  • 第二个是最快的。
  • 作为一个习惯在 Minecraft 模组中使用 Mixins 的人,第二个似乎是明显的赢家。
  • 第五个选项(正如大多数答案所说)是: int i = (int)e; (不先转换为对象)
  • @andreyk2Hohlov Cannot convert type 'System.Enum' to 'int'
【解决方案5】:
Question question = Question.Role;
int value = (int) question;

将导致value == 2

【讨论】:

  • 类似这样的 Questions.Get(Convert.ToInt16(Question.Applications))
  • 您可以简单地向任一方向投射;唯一需要注意的是枚举不强制执行任何操作(枚举值可能是 288,即使该数字不存在任何问题)
  • @jim:不,只需转换值:Questions.Get((int)Question.Applications);
【解决方案6】:

这比您想象的要容易 - 枚举已经是 int。只是需要提醒一下:

int y = (int)Question.Role;
Console.WriteLine(y); // Prints 2

【讨论】:

  • Nitpick:this 枚举已经是一个 int。其他枚举可能是不同的类型——试试 "enum SmallEnum : byte { A, B, C }"
  • 绝对正确。 C# 参考:“每个枚举类型都有一个基础类型,它可以是除 char 之外的任何整数类型。”
【解决方案7】:

例子:

public enum EmpNo
{
    Raj = 1,
    Rahul,
    Priyanka
}

并在后面的代码中获取枚举值:

int setempNo = (int)EmpNo.Raj; // This will give setempNo = 1

int setempNo = (int)EmpNo.Rahul; // This will give setempNo = 2

Enums 将递增 1,您可以设置起始值。如果你没有设置起始值,它最初会被赋值为 0。

【讨论】:

  • Raj 的东西也可以是 Rahul 或 Priyanka 吗?你的价值观有冲突,应该加倍才能独一无二,例如0、1、2、4、8等。这是我对枚举的核心关注。
  • @TimothyGonzalez 实际上,如果你没有明确指定它们的值,枚举只会加 1 ;)
  • @derHugo 这取决于您假设数值是以 10 为底还是以 2 为底。
  • @TimothyGonzalez 好吧,没什么好假设的......我只是指出,默认情况下,它们只会在 int 中计算 1,除非您明确定义其他方式
【解决方案8】:

我最近在我的代码中不再使用枚举,而是使用具有受保护构造函数和预定义静态实例的类(感谢 Roelof - C# Ensure Valid Enum Values - Futureproof Method)。

鉴于此,下面是我现在处理此问题的方法(包括与int 的隐式转换)。

public class Question
{
    // Attributes
    protected int index;
    protected string name;
    // Go with a dictionary to enforce unique index
    //protected static readonly ICollection<Question> values = new Collection<Question>();
    protected static readonly IDictionary<int,Question> values = new Dictionary<int,Question>();

    // Define the "enum" values
    public static readonly Question Role = new Question(2,"Role");
    public static readonly Question ProjectFunding = new Question(3, "Project Funding");
    public static readonly Question TotalEmployee = new Question(4, "Total Employee");
    public static readonly Question NumberOfServers = new Question(5, "Number of Servers");
    public static readonly Question TopBusinessConcern = new Question(6, "Top Business Concern");

    // Constructors
    protected Question(int index, string name)
    {
        this.index = index;
        this.name = name;
        values.Add(index, this);
    }

    // Easy int conversion
    public static implicit operator int(Question question) =>
        question.index; //nb: if question is null this will return a null pointer exception

    public static implicit operator Question(int index) =>        
        values.TryGetValue(index, out var question) ? question : null;

    // Easy string conversion (also update ToString for the same effect)
    public override string ToString() =>
        this.name;

    public static implicit operator string(Question question) =>
        question?.ToString();

    public static implicit operator Question(string name) =>
        name == null ? null : values.Values.FirstOrDefault(item => name.Equals(item.name, StringComparison.CurrentCultureIgnoreCase));


    // If you specifically want a Get(int x) function (though not required given the implicit converstion)
    public Question Get(int foo) =>
        foo; //(implicit conversion will take care of the conversion for you)
}

这种方法的优点是您可以从枚举中获得所有内容,但是您的代码现在更加灵活,因此如果您需要根据 Question 的值执行不同的操作,您可以将逻辑放入 @ 987654326@ 本身(即以首选的 OO 方式),而不是在整个代码中放置大量案例语句来处理每种情况。


注意:答案于 2018-04-27 更新以利用 C# 6 功能;即声明表达式和 lambda 表达式主体定义。原始代码见revision history。这样做的好处是使定义不那么冗长;这是对此答案方法的主要抱怨之一。

【讨论】:

  • 我想这是显式强制转换和您必须编写的代码之间的权衡。仍然喜欢实施只是希望它不是那么长。 +1
  • 我使用了几种不同类型的类,其结构与此类似。我发现在尝试遵循“以后不要让我成为白痴”的方法时,它们会产生奇迹。
【解决方案9】:

如果您想获取存储在变量中的枚举值的整数,其类型为Question,例如在方法中使用,您可以简单地执行我在此示例中编写的操作:

enum Talen
{
    Engels = 1, Italiaans = 2, Portugees = 3, Nederlands = 4, Duits = 5, Dens = 6
}

Talen Geselecteerd;    

public void Form1()
{
    InitializeComponent()
    Geselecteerd = Talen.Nederlands;
}

// You can use the Enum type as a parameter, so any enumeration from any enumerator can be used as parameter
void VeranderenTitel(Enum e)
{
    this.Text = Convert.ToInt32(e).ToString();
}

这会将窗口标题更改为 4,因为变量 GeselecteerdTalen.Nederlands。如果我将其更改为Talen.Portugees 并再次调用该方法,则文本将更改为3。

【讨论】:

  • 不幸的是,这种方法使用得越多,性能就越差。我在我的一些代码中尝试过,随着时间的推移,我的应用程序变得越来越慢,CPU 使用率越来越低。这意味着线程正在等待某些东西 - 我假设某种垃圾收集,可能是由于将枚举参数装箱到 ToInt32()。通过切换到一个简单的 int.Parse(),我能够完全消除这种糟糕的性能,并且无论代码运行多长时间,性能都保持不变。
【解决方案10】:

另一种方法:

Console.WriteLine("Name: {0}, Value: {0:D}", Question.Role);

这将导致:

Name: Role, Value: 2

【讨论】:

  • 这是我用例的最佳解决方案,因为我的枚举是 int 和 long 值的混合
【解决方案11】:

要确保枚举值存在然后解析它,您还可以执行以下操作。

// Fake Day of Week
string strDOWFake = "SuperDay";

// Real Day of Week
string strDOWReal = "Friday";

// Will hold which ever is the real DOW.
DayOfWeek enmDOW;

// See if fake DOW is defined in the DayOfWeek enumeration.
if (Enum.IsDefined(typeof(DayOfWeek), strDOWFake))
{
    // This will never be reached since "SuperDay"
    // doesn't exist in the DayOfWeek enumeration.
    enmDOW = (DayOfWeek)Enum.Parse(typeof(DayOfWeek), strDOWFake);
}
// See if real DOW is defined in the DayOfWeek enumeration.
else if (Enum.IsDefined(typeof(DayOfWeek), strDOWReal))
{
    // This will parse the string into it's corresponding DOW enum object.
    enmDOW = (DayOfWeek)Enum.Parse(typeof(DayOfWeek), strDOWReal);
}

// Can now use the DOW enum object.
Console.Write("Today is " + enmDOW.ToString() + ".");

【讨论】:

    【解决方案12】:

    改用扩展方法:

    public static class ExtensionMethods
    {
        public static int IntValue(this Enum argEnum)
        {
            return Convert.ToInt32(argEnum);
        }
    }
    

    而且用法稍微漂亮一点:

    var intValue = Question.Role.IntValue();
    

    【讨论】:

      【解决方案13】:

      也许我错过了,但有人尝试过简单的通用扩展方法吗?

      这对我很有用。您可以通过这种方式避免 API 中的类型转换,但最终会导致更改类型操作。这是对Roslyn 进行编程以让编译器为您创建 GetValue 方法的好案例。

          public static void Main()
          {
              int test = MyCSharpWrapperMethod(TestEnum.Test1);
      
              Debug.Assert(test == 1);
          }
      
          public static int MyCSharpWrapperMethod(TestEnum customFlag)
          {
              return MyCPlusPlusMethod(customFlag.GetValue<int>());
          }
      
          public static int MyCPlusPlusMethod(int customFlag)
          {
              // Pretend you made a PInvoke or COM+ call to C++ method that require an integer
              return customFlag;
          }
      
          public enum TestEnum
          {
              Test1 = 1,
              Test2 = 2,
              Test3 = 3
          }
      }
      
      public static class EnumExtensions
      {
          public static T GetValue<T>(this Enum enumeration)
          {
              T result = default(T);
      
              try
              {
                  result = (T)Convert.ChangeType(enumeration, typeof(T));
              }
              catch (Exception ex)
              {
                  Debug.Assert(false);
                  Debug.WriteLine(ex);
              }
      
              return result;
          }
      }
      

      【讨论】:

      • 可能是因为执行 (int)customFlag 减少了到处打字,而且或多或少做了同样的事情?
      • Re "可能我错过了,但是有没有人尝试过简单的通用扩展方法?"SixOThree said"使用扩展方法而不是"Bronek said "你可以通过为你定义的枚举类型实现一个扩展方法来做到这一点"
      【解决方案14】:
      public enum QuestionType
      {
          Role = 2,
          ProjectFunding = 3,
          TotalEmployee = 4,
          NumberOfServers = 5,
          TopBusinessConcern = 6
      }
      

      ...是一个很好的声明。

      您必须像这样将结果转换为 int:

      int Question = (int)QuestionType.Role
      

      否则,类型仍然是QuestionType

      这种严格程度是 C# 的方式。

      另一种方法是使用类声明:

      public class QuestionType
      {
          public static int Role = 2,
          public static int ProjectFunding = 3,
          public static int TotalEmployee = 4,
          public static int NumberOfServers = 5,
          public static int TopBusinessConcern = 6
      }
      

      声明不太优雅,但您不需要在代码中强制转换:

      int Question = QuestionType.Role
      

      或者,您可能对 Visual Basic 感到更自在,它在许多领域都能满足这种期望。

      【讨论】:

        【解决方案15】:
        int number = Question.Role.GetHashCode();
        

        number 的值应为 2

        【讨论】:

        • GetHashCode 是从 Enum 通用掩码中获取值的一种方法
        • 请注意,这只是 bool*、byteushortintuint** 的“合法”。其他类型的 GetHashCode 会修改值,例如做一些位移和异或。 (* 1 / 0,**当然是转换为 int)。但总而言之,除非它是您自己的私有代码,否则不要这样做。
        【解决方案16】:

        用途:

        Question question = Question.Role;
        int value = question.GetHashCode();
        

        这将导致value == 2

        仅当枚举适合 int 时才适用。

        【讨论】:

        • 只有当枚举适合 int 时才成立,因为 GetHashCode 返回一个整数。
        【解决方案17】:

        您可以通过为您定义的枚举类型实现extension method 来做到这一点:

        public static class MyExtensions
        {
            public static int getNumberValue(this Question questionThis)
            {
                return (int)questionThis;
            }
        }
        

        这简化了获取当前枚举值的int值:

        Question question = Question.Role;
        int value = question.getNumberValue();
        

        int value = Question.Role.getNumberValue();
        

        【讨论】:

        • Bronek,您所做的是通过(非通用 btw)扩展方法组成无信息语法,实际上需要更长的时间来编写。我看不出它比 Tetraneutron 的原始解决方案更好。让我们不要把它变成聊天,stackoverflow 总是欢迎帮助,这里的每个人都在这里提供帮助。请把我的评论当作建设性的批评。
        • 本杰明,首先,你为什么要删除我的评论?我不明白你的决定——也许社区中的其他人会同意我的评论。其次,我的解决方案准确地包装了 Tetraneutron 的解决方案由于 IntelliSense 建议了扩展方法,因此更容易编写更少。所以我认为您的决定不公正和具有代表性。我在 Stack 上看到了许多类似的答案,没关系。无论如何我使用我的解决方案,也许有些人会将来选择我的解决方案,但这些负面因素使我更难找到。最重要的是它是正确的,而不是复制。
        • @Bronek 如果你不 ping 我,我看不到你回复的迹象。我确实没有删除您的评论我没有能力或不想这样做。可能有一个模组过来并删除了它 - 欢迎您将其标记为版主注意并询问原因或更好 - 在Meta Stack Overflow上提问。从编程的角度来看,我对您的解决方案有一个意见,这完全符合我的权利 - 这就是 cmets 的初衷,无需将其视为个人。
        【解决方案18】:
        public enum Suit : int
        {
            Spades = 0,
            Hearts = 1,
            Clubs = 2,
            Diamonds = 3
        }
        
        Console.WriteLine((int)(Suit)Enum.Parse(typeof(Suit), "Clubs"));
        
        // From int
        Console.WriteLine((Suit)1);
        
        // From a number you can also
        Console.WriteLine((Suit)Enum.ToObject(typeof(Suit), 1));
        
        if (typeof(Suit).IsEnumDefined("Spades"))
        {
            var res = (int)(Suit)Enum.Parse(typeof(Suit), "Spades");
            Console.Out.WriteLine("{0}", res);
        }
        

        【讨论】:

        • 按顺序解释示例代码(editing your answer,不在 cmets 中)。
        • 零通常保留用于枚举中的未设置/未知状态,这样定义是不寻常的
        【解决方案19】:

        由于可以使用多种基本类型声明枚举,因此转换任何枚举类型的通用扩展方法可能很有用。

        enum Box
        {
            HEIGHT,
            WIDTH,
            DEPTH
        }
        
        public static void UseEnum()
        {
            int height = Box.HEIGHT.GetEnumValue<int>();
            int width = Box.WIDTH.GetEnumValue<int>();
            int depth = Box.DEPTH.GetEnumValue<int>();
        }
        
        public static T GetEnumValue<T>(this object e) => (T)e;
        

        【讨论】:

          【解决方案20】:

          试试这个,而不是将 enum 转换为 int:

          public static class ReturnType
          {
              public static readonly int Success = 1;
              public static readonly int Duplicate = 2;
              public static readonly int Error = -1;        
          }
          

          【讨论】:

            【解决方案21】:

            以下是扩展方法

            public static string ToEnumString<TEnum>(this int enumValue)
            {
                var enumString = enumValue.ToString();
                if (Enum.IsDefined(typeof(TEnum), enumValue))
                {
                    enumString = ((TEnum) Enum.ToObject(typeof (TEnum), enumValue)).ToString();
                }
                return enumString;
            }
            

            【讨论】:

              【解决方案22】:

              我能想到的最简单的解决方案是像这样重载Get(int) 方法:

              [modifiers] Questions Get(Question q)
              {
                  return Get((int)q);
              }
              

              其中[modifiers] 通常可以与Get(int) 方法相同。如果您无法编辑Questions 类或出于某种原因不想编辑,您可以通过编写扩展来重载该方法:

              public static class Extensions
              {
                  public static Questions Get(this Questions qs, Question q)
                  {
                      return qs.Get((int)q);
                  }
              }
              

              【讨论】:

                【解决方案23】:

                我最喜欢使用 int 或更小枚举的 hack:

                GetHashCode();
                

                对于一个枚举

                public enum Test
                {
                    Min = Int32.MinValue,
                    One = 1,
                    Max = Int32.MaxValue,
                }
                

                这个,

                var values = Enum.GetValues(typeof(Test));
                
                foreach (var val in values)
                {
                    Console.WriteLine(val.GetHashCode());
                    Console.WriteLine(((int)val));
                    Console.WriteLine(val);
                }
                

                输出

                one
                1
                1
                max
                2147483647
                2147483647
                min
                -2147483648
                -2147483648
                

                免责声明:

                它不适用于基于 long 的枚举。

                【讨论】:

                  【解决方案24】:

                  我想建议“从枚举中获取 'int' 值”的示例是

                  public enum Sample
                  {
                      Book = 1, 
                      Pen = 2, 
                      Pencil = 3
                  }
                  
                  int answer = (int)Sample.Book;
                  

                  现在答案是 1。

                  【讨论】:

                    【解决方案25】:

                    您应该使用Type Casting,因为我们可以在任何其他语言中使用。

                    如果你的enum是这样的-

                    public enum Question
                    {
                        Role = 2,
                        ProjectFunding = 3,
                        TotalEmployee = 4,
                        NumberOfServers = 5,
                        TopBusinessConcern = 6
                    }
                    

                    你需要转换为int,然后执行此操作-

                    Question q = Question.Role;
                    .............
                    .............
                    int something = (int) q;
                    

                    重新-

                    在 C# 中,有两种类型的转换:

                    • 隐式转换(自动 - 将较小的类型转换为较大的类型,例如 -

                    char -> int -> long -> float -> double

                    • 显式转换(手动 - 将较大的类型转换为较小的类型,例如 -

                    double -> float -> long -> int -> char

                    更多信息请访问here

                    【讨论】:

                      【解决方案26】:

                      在 Visual Basic 中,它应该是:

                      Public Enum Question
                          Role = 2
                          ProjectFunding = 3
                          TotalEmployee = 4
                          NumberOfServers = 5
                          TopBusinessConcern = 6
                      End Enum
                      
                      Private value As Integer = CInt(Question.Role)
                      

                      【讨论】:

                        【解决方案27】:

                        会给你一个包含枚举所有整数值的列表:

                        列出 enumValues = Enum.GetValues(typeof(EnumClass)).Cast().ToList();

                        【讨论】:

                          【解决方案28】:
                          public enum ViewType
                          {
                              List = 1,
                              Table = 2,
                          };
                                      
                          // You can use the Enum type as a parameter, so any enumeration from any enumerator 
                          // cshtml
                          // using proyects.Helpers
                          // @if (Model.ViewType== (int)<variable>.List )
                          

                          【讨论】:

                            【解决方案29】:

                            我想出了这个包含当前语言功能的扩展方法。通过使用动态,我不需要将其设为通用方法并指定使调用更简单和一致的类型:

                            public static class EnumEx
                            {
                                public static dynamic Value(this Enum e)
                                {
                                    switch (e.GetTypeCode())
                                    {
                                        case TypeCode.Byte:
                                        {
                                            return (byte) (IConvertible) e;
                                        }
                            
                                        case TypeCode.Int16:
                                        {
                                            return (short) (IConvertible) e;
                                        }
                            
                                        case TypeCode.Int32:
                                        {
                                            return (int) (IConvertible) e;
                                        }
                            
                                        case TypeCode.Int64:
                                        {
                                            return (long) (IConvertible) e;
                                        }
                            
                                        case TypeCode.UInt16:
                                        {
                                            return (ushort) (IConvertible) e;
                                        }
                            
                                        case TypeCode.UInt32:
                                        {
                                            return (uint) (IConvertible) e;
                                        }
                            
                                        case TypeCode.UInt64:
                                        {
                                            return (ulong) (IConvertible) e;
                                        }
                            
                                        case TypeCode.SByte:
                                        {
                                            return (sbyte) (IConvertible) e;
                                        }
                                    }
                            
                                    return 0;
                                }
                            

                            【讨论】:

                            • 请不要,您可以在一行中完成所有这些 Convert.Changetype(e, e.GetTypeCode()) 并取回一个对象,不需要动态或扩展方法
                            • 我不同意使用 Convert。仅使用演员表会更容易。我的意图是能够在不使用强制转换的情况下将任何枚举转换为它的值。这允许更改枚举类型而不必更改所有相关的强制转换 - 但是什么时候会发生这种情况?扩展方法正常工作。但是,我有一个问题,因为它是动态的,编译器无法类型检查(显然是整个语句),这意味着在运行时会发生类型检查 - 这不是一个好的解决方案。我想我会回到演员阵容。
                            • 我没有说过度使用它,只是这段代码毫无意义,什么也没做,实际上使问题变得更糟。我建议删除此解决方案
                            猜你喜欢
                            • 1970-01-01
                            • 2014-02-02
                            • 1970-01-01
                            • 2017-10-08
                            • 2013-04-07
                            • 1970-01-01
                            • 2010-11-03
                            相关资源
                            最近更新 更多