简体   繁体   English

System.Drawing.Color Struct如何初始化颜色?

[英]How Does System.Drawing.Color Struct Initialize Colors?

I need to create a type that contains a few methods and a long list of constants. 我需要创建一个包含一些方法和一长串常量的类型。

After a little research, I think I'd like to take the same approach taken by the System.Drawing.Color struct. 经过一番研究后,我想我想采用System.Drawing.Color结构采用的相同方法。 However, looking at the source for this structure (generated from meta data) gives me something like the following. 但是,查看此结构的源(从元数据生成)给出了类似下面的内容。

public byte A { get; }
public static Color AliceBlue { get; }
public static Color AntiqueWhite { get; }
public static Color Aqua { get; }
public static Color Aquamarine { get; }
public static Color Azure { get; }
public byte B { get; }
// ...

Can anyone explain to me how the static Color values (which are the same type as the containing struct) ever get initialized? 任何人都可以向我解释静态颜色值(与包含结构的类型相同)是如何初始化的? I must be missing something. 我肯定错过了什么。

If you look at the Color class with Reflector you will see: 如果您使用Reflector查看Color类,您将看到:

public static Color AliceBlue
{
    get
    {
        return new Color(KnownColor.AliceBlue);
    }
}

That confirms that a new Color object is returned every time. 这确认每次都返回一个新的Color对象。

Using the .NET Reflector (derived code below), we can see that a new color struct is created each time the static Color property (ex: AliceBlue) is called. 使用.NET Reflector(下面的派生代码),我们可以看到每次调用静态Color属性(例如:AliceBlue)时都会创建一个新的颜色结构。 Microsoft probably implemented it this way to ensure immutable values for this property. Microsoft可能以这种方式实现它以确保此属性的不可变值。

public static Color AliceBlue
{
    get
    {
        return new Color(KnownColor.AliceBlue);
    }
}

An internal constructor is called and passes an enum value (KnownColor.AliceBlue) to the contstructor. 调用内部构造函数并将枚举值(KnownColor.AliceBlue)传递给contstructor。 The Color structure stores this enum and sets a flag/state that it is a known color. Color结构存储此枚举并设置它是已知颜色的标志/状态。

internal Color(KnownColor knownColor)
{
    this.value = 0L;
    this.state = StateKnownColorValid;
    this.name = null;
    this.knownColor = (short) knownColor;
}

Further, from analyzing the .NET Reflector code, when you try to get a value out of the Color structure (such as the R property), the property does a search on a lookup table (ie private static array) using the knownColor enum and returns an Int64 representing all of the color information. 此外,通过分析.NET Reflector代码,当您尝试从Color结构中获取值(例如R属性)时,该属性使用knownColor枚举对查找表(即私有静态数组)进行搜索,返回表示所有颜色信息的Int64 From there it does some bit manipulation (bitwise AND, bit shifts, etc.) to come up with the byte representing the R (or G or B , etc.) value. 从那里它进行一些位操作(按位AND,位移等)以得出表示R (或GB等)值的字节。

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

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