繁体   English   中英

无法为枚举赋值

[英]Failing to assign a value to an enum

您是否曾经有一天没有任何工作? 现在,我什至无法成功设置枚举的值!

我在底部的Enum.Parse语句时遇到了麻烦,因此我在其上方编写了“ if”块。 令我惊讶的是,这也失败了。

我是用调试器跟踪的。 字符串x值为“ OnDemand”。 采取第一个'if's“ true”分支,但bitmapCacheOption保留为BitmapCacheOption.Default

下面的Enum.Parse表达式也是Enum.Parse 所以我的问题是: 在给枚举赋值时我做错了什么?

BitmapCacheOption bitmapCacheOption;
if (x == "OnDemand") bitmapCacheOption = BitmapCacheOption.OnDemand;
else
{
   if (x == "OnLoad") bitmapCacheOption = BitmapCacheOption.OnLoad;
   else
   {
      if (x == "None") bitmapCacheOption = BitmapCacheOption.None;
      else bitmapCacheOption = BitmapCacheOption.Default;
   }
}
BitmapCacheOption bitmapCacheOption1 =
            (BitmapCacheOption)Enum.Parse(typeof(BitmapCacheOption), x, false);
Debug.Assert(bitmapCacheOption == bitmapCacheOption1);

编辑 :问题中的枚举是WPF BitmapCacheOption Enum.Parse语句末尾的false只是意味着忽略大小写。 我知道编写级联的“ if”语句(包括“ else if”和“ switch”语句)的更好方法,但是所有这些都不在问题之列。 我在调试过程中以这种方式编写了“ if”,以便我逐步调试。 重要的是,即使简单,如果x等于“ OnDemand”,bitmapCacheOption仍保持BitmapCacheOption.Default!

编辑 :请注意调试器的“本地”窗口中“ bitmapCacheOption”的值-即使黄色高亮显示未使用“ OnDemand”开关盒,它也保持在“默认”状态!

调试器快照:

尝试删除错误的运算符-

BitmapCacheOption bitmapCacheOption1 =
            (BitmapCacheOption)Enum.Parse(typeof(BitmapCacheOption), x);

并在路上-上传Enum结构供我们查看是否有问题。

编辑:哇!

在此处输入图片说明

看起来他们有一个错误- 两者的索引都为0。这就是为什么每次都获得默认值的原因。 因为它是0。很好...但是当您将值设置为x时-它为他分配了0而不是应该存在的YYY值。

你在这里没做错什么...

看一下Enum的定义:

// Summary:
//     Specifies how a bitmap image takes advantage of memory caching.
public enum BitmapCacheOption
{
    // Summary:
    //     Creates a memory store for requested data only. The first request loads the
    //     image directly; subsequent requests are filled from the cache.
    OnDemand = 0,
    //
    // Summary:
    //     Caches the entire image into memory. This is the default value.
    Default = 0,
    //
    // Summary:
    //     Caches the entire image into memory at load time. All requests for image
    //     data are filled from the memory store.
    OnLoad = 1,
    //
    // Summary:
    //     Do not create a memory store. All requests for the image are filled directly
    //     by the image file.
    None = 2,
}

OnDemandDefault均为0;)

因此,您不能依赖于将0的字符串表示形式转换为BitmapCacheOption的值。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM