Using a OR'ed Enum in a custom UITypeEditor

2020-05-09 04:34发布

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:

Code generation for the property 'TrayMode' failed. Error was: 'The value '9' is not valid for the enum 'TrayModes'.'

2条回答
祖国的老花朵
2楼-- · 2020-05-09 05:04

Using the Flags attribute on the enum will prevent the error from happening. This is a mystery to me as storing an ORed enum without the flag is valid and can be done in the code (With a proper cast).

查看更多
成全新的幸福
3楼-- · 2020-05-09 05:08

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.aspx A To string of enum with and without Flags attribute show how they are different

All possible combinations of values of an Enum 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 an Enum 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
查看更多
登录 后发表回答