列挙型System.Reflection.TypeAttributes
はかなり病的です。それは属性を持っており、定数ゼロの同義語が4 つ[Flags]
以上あります。Visual Studio で生成された「メタデータ」から:
#region Assembly mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
// C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.6.2\mscorlib.dll
#endregion
using System.Runtime.InteropServices;
namespace System.Reflection
{
//
// Summary:
// Specifies type attributes.
[ComVisible(true)]
[Flags]
public enum TypeAttributes
{
//
// Summary:
// Specifies that the class is not public.
NotPublic = 0,
//
// Summary:
// Specifies that class fields are automatically laid out by the common language
// runtime.
AutoLayout = 0,
//
// Summary:
// Specifies that the type is a class.
Class = 0,
//
// Summary:
// LPTSTR is interpreted as ANSI.
AnsiClass = 0,
// (followed by non-zero members...)
を運ぶ列挙型でゼロに4つの名前を使用するのはなぜFlagsAttribute
ですか? 本当にクレイジーなようです。
結果を見てください:
var x = default(System.Reflection.TypeAttributes); // 0
var sx = x.ToString(); // "NotPublic"
var y = (System.Reflection.TypeAttributes)(1 << 20); // 1048576
var sy = y.ToString(); // "AutoLayout, AnsiClass, Class, BeforeFieldInit"
x
ここで、型のゼロ値であるの文字列表現はになり"NotPublic"
ます。ゼロ以外の文字列表現y
は"AutoLayout, AnsiClass, Class, BeforeFieldInit"
. に関しては、1 つのビット セット ( ) しかなく、名前だけでそのビットを正確に説明してy
いることに注意してください。他の 3 つの名前 はすべて、値にゼロで寄与します。1<<20
BeforeFieldInit
AutoLayout, AnsiClass, Class,
何が起こっている?
なぜこのデザイン?