在自定义UITypeEditor中使用OR

在自定义UITypeEditor中使用OR

本文介绍了在自定义UITypeEditor中使用OR'ed枚举的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个自定义控件的属性,我写的是一个基于标志的枚举。我创建了自己的自定义控件来编辑它,使其具有逻辑意义,并从我自己的UITypeEditor中调用它。问题是,当我尝试存储的值是它告诉我该值无效的标志的组合时,Visual Studio会生成错误。



示例:

  public enum TrayModes 
{
SingleUnit = 0x01
,Tray = 0x02
,Poll = 0x04
,Trigger = 0x08
};

如果要保存的值为 SingleUnit |触发器生成的值为9.这反过来又会产生以下错误:



$ b $你必须在你的枚举声明之前添加[Flags]

[Flags] $ {$ class =h2_lin>解决方案

b $ b public enum TrayModes
{
SingleUnit = 0x01
,Tray = 0x02
,Poll = 0x04
,Trigger = 0x08
};

考虑使用HasFlag函数检查已设置的标志

  TrayModes t = TrayModes.SingleUnit | TrayModes.Poll; 
if(t.HasFlag(TrayModes.SingleUnit))
// return true

编辑:
这是因为具有flags属性的枚举以不同的方式处理,
,您可以在
A到一个枚举的字符串有和没有Flags属性显示它们是如何不同的




的值的所有可能组合没有FlagsAttribute的枚举:

  0  - 黑色
1 - 红色
2 - 绿色
3 - 3
4 - 蓝色
5 - 5
6 - 6
7 - 7
8 - 8


的值的所有可能组合与FlagsAttribute的枚举:

  0  -  Black 
1 - 红色
2 - 绿色
3 - 红色,绿色
4 - 蓝色
5 - 红色,蓝色
6 - 绿色,蓝色
7 - 红色,绿色,蓝色e
8 - 8


I have a property on a custom control I have written that is an Flag based Enum. I created my own custom control to edit it in a way that makes logical sense and called it from my own UITypeEditor. The problem is that Visual Studio generates an error when the value I attempt to store is a combination of the flags it tells me the value is invalid.

Example:

public enum TrayModes
{
    SingleUnit = 0x01
  , Tray = 0x02
  , Poll = 0x04
  , Trigger = 0x08
};

If the value I want to save is SingleUnit | Trigger the value generated is 9. Which in turn creates the following error:

解决方案
You have to add [Flags] before your enum declaration

[Flags]
public enum TrayModes
{
    SingleUnit = 0x01
   , Tray = 0x02
   , Poll = 0x04
   , Trigger = 0x08
};

Consider using HasFlag function to check for setted flags

TrayModes t=TrayModes.SingleUnit|TrayModes.Poll;
if(t.HasFlag(TrayModes.SingleUnit))
//return true

Edit:That's because enum with flags attribute are threated in a different way,as you can see in the example in http://msdn.microsoft.com/en-us/library/system.flagsattribute.aspxA To string of enum with and without Flags attribute show how they are different

All possible combinations of values of anEnum without FlagsAttribute:

  0 - Black
  1 - Red
  2 - Green
  3 - 3
  4 - Blue
  5 - 5
  6 - 6
  7 - 7
  8 - 8

All possible combinations of values of anEnum with FlagsAttribute:

  0 - Black
  1 - Red
  2 - Green
  3 - Red, Green
  4 - Blue
  5 - Red, Blue
  6 - Green, Blue
  7 - Red, Green, Blue
  8 - 8

这篇关于在自定义UITypeEditor中使用OR'ed枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 10:23