【问题标题】:Getting error when trying to enumerate enum尝试枚举枚举时出错
【发布时间】:2016-11-09 12:57:54
【问题描述】:

我有以下型号:

public class FormModel
{
  public Guid {get; set;}
  public Sections Sections {get; set}
}

[Flags]
    public enum Sections
    {
        Test1= 0,
        Test2= 1,
        Test3= 2,
        Test4= 4,
        Test5= 8,
        Test6= 16
    }

我正在使用一个返回模型数据的服务:

var form = await _formService.GetById(formAnswer.FormId);

现在 Sections-property 包含:Test1 | Test2

我正在尝试像这样枚举这个属性:

 var list = new List<string>();
 foreach(var item in Enum.GetValues(typeof(form.Sections)))
 {
     //Add the form.Sections into the list.
 }

但我得到了错误:

'form' 是一个变量,但用作类型

如何枚举模型的 Sections 属性并将值添加到列表中?

【问题讨论】:

  • 类型为typeof(Sections)。您将某些 Sections 值传递给typeof
  • 使用 form.Sections.GetType()
  • @CharlesMager:那么我应该怎么做 insead?
  • @Bryan 就像我说的 - typeof(Sections).
  • @CharlesMager:但如果我这样做,我会枚举整个枚举。不是我的服务结果中的 Sections-property..

标签: c# asp.net-mvc enums


【解决方案1】:

你有一个错字。您使用了表单实例,而不是您想要枚举的类型。试试:

foreach (var item in Enum.GetValues(typeof(Sections)))
{
    if (((int)form.Sections & (int)item) != 0)
    {
         // add to list
    }
}

【讨论】:

  • 但如果我这样做,我会枚举整个枚举。不是我的服务结果中的 Sections-property..
  • @Bryan Ah,现在我知道你想要什么了,检查更新
  • 呵呵,我之前试过像你这样回答:if ((int)form.Sections & (int)item) > 0) { },但我得到了一个错误。现在我看到我忘记了括号。谢谢!
  • 您也可以使用if(form.Sections.HasFlag(item)),隐藏强制转换和布尔逻辑。
猜你喜欢
  • 2023-03-27
  • 2010-12-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-06
  • 1970-01-01
  • 2011-03-22
相关资源
最近更新 更多