【问题标题】:enum refuses to convert to String枚举拒绝转换为字符串
【发布时间】:2012-06-04 09:26:32
【问题描述】:

奇怪的是,我有两个枚举集:

public enum ComponentActionTypes {
    Add = 0,
    Move = 1,
    Delete = 2,
    Edit = 3,
    Enable = 4,
    Disable = 5
}
public enum ComponentNames {
    Component = 0,
    Logo = 1,
    Main_menu = 2,
    Search_box = 3,
    Highlighter = 4,
    RSS = 5,
    Twitter = 6,
    YouTube = 7
}

当我尝试打印以下文本时,

ActionText =
string.Format("{0}ed a {1}", action.ComponentActionType, action.ComponentName);

将生成:

184ed a Logo 而不是Added a Logo

action.ComponentActionType 被转换为数字(ToString 没有帮助),也是一个

奇怪的数字(如184,而不是枚举数本身)

知道如何解决这个问题吗?

更新:

namespace BrandToolbar.Common.ActionLog.Model
{
    public class ActionItem
    {
        public Guid UserId { get; set; }
        public Int64 PublicId { get; set; }
        public ComponentActionTypes ComponentActionType { get; set; }
        public DateTime Date { get; set; }
        public ComponentNames ComponentName { get; set; }
        public string UiJsonPreview { get; set; }
    }
}


public static ActionItemUI ConvertModelToUiObj(ActionItem action)
{
    return new ActionItemUI()
    {
        ActionText = string.Format(
            "{0}ed a {1}",
            action.ComponentActionType,
            action.ComponentName
        ).Replace("_", " "),
        TooltipText = string.Format(
            "{0}ed on {1}",
            action.ComponentActionType,
            action.Date.ToString(StringFormatter.DateFormat)
        ),
        ImageUrl = string.Empty,
        ConponentText = string.Empty
    };
}

【问题讨论】:

  • 你确定action.ComponentActionType 真的是ComponentActionTypes 类型吗?
  • 可能是个蹩脚的问题,但你确定 action.ComponentActionType 是 ComponentActionTypes 类型吗?我认为 .ToString() 至少会给你你需要的东西
  • 你能展示创建你的动作对象的代码吗?此外,Action 类可能很有用。

标签: c# logging enums c#-3.0


【解决方案1】:

ComponentActionTypes.Add 的值 == 0。代码示例中的 action.ComponentActionType 的值 == 184。只要枚举变量允许存储不在枚举定义中的值,您就会得到这样的结果。

你需要检查一下,为什么action.ComponentActionType等于184。

【讨论】:

    【解决方案2】:

    你能检查一下 ComponentActionType 字段是如何填充的吗?枚举值可以包含未列出的其他值。例如:这是完全有效的:

        enum foo {A = 1,B = 2,C = 3};
        var b = (foo)7;
    

    (如果默认情况下不允许,则无法使用枚举进行屏蔽)。在这种情况下,b 的字符串表示为 7,因为它无法与枚举中的项目匹配。

    【讨论】:

      【解决方案3】:

      试试

      Enum.GetName(typeof(ComponentActionTypes), action.ComponentAction);
      

      不确定“184”通过。

      【讨论】:

        猜你喜欢
        • 2012-08-25
        • 2010-10-03
        • 1970-01-01
        • 2014-03-18
        • 2015-06-10
        • 1970-01-01
        • 1970-01-01
        • 2016-07-30
        相关资源
        最近更新 更多