FlagsAttribute つきの Enum の挙動
2003年10月8日(水曜日)
FlagsAttribute つきの Enum の挙動
FlagsAttribute のついた Enum が謎の挙動を見せています。
こんな感じのテストプログラムで……
using System;
class App{
public static int Main(string[] args){
if(args.Length == 0){
Console.WriteLine("引数を指定してください。");
return 1;
}
string versionStr = args[0];
HtmlVersions h;
try{
h = (HtmlVersions)Enum.Parse(typeof(HtmlVersions), versionStr);
} catch(Exception e){
Console.WriteLine(e.Message);
return 1;
}
Console.WriteLine(h);
return 0;
}
[FlagsAttribute]
public enum HtmlVersions {
None,
h10, h20, h2x, h30, hp,
h32,
h40, h40t, h40f,
h401, h401t, h401f,
x10, x10t, x10f,
x11,
x20
}
}
"h40,x20" と指定すると "h40, x20" と表示されることを期待しているのですが、何故か "h10, x20" という結果になります。しかし Enum の各値に全部数値を指定して、
[FlagsAttribute]
public enum HtmlVersions{
None = 0,
h10 = 1, h20 = 2, h2x = 4, h30 = 8, hp = 16,
h32 = 32,
h40 = 64, h40t = 128, h40f = 512,
h401 = 1024, h401t = 2048, h401f = 4096,
x10 = 8192, x10t = 16384, x10f = 32756,
x11 = 65536,
x20 = 131072
}
とやると、期待通りに動作します。[FlagsAttribute] を指定したら自動的に後者のようにしてくれると思っていたのですが、そうではないのですね。
- 「FlagsAttribute つきの Enum の挙動」にコメントを書く
- 前(古い): 秀丸で「を」が入力できないことがある
- 次(新しい): エンディングいっこめ
