更改可写后备字段后,C#中的只读属性将永远不会更新

时间:2018-12-14 19:28:57

标签: c#

我在下面实现了一个非常简单的Color类:

using System;
namespace HelloWorld
{
    internal class Color
    {
        private byte red;
        private byte green;
        private byte blue;
        private byte alpha;

        public Color(byte red, byte green, byte blue, byte alpha)
        {
            this.red = red;
            this.green = green;
            this.blue = blue;
            this.alpha = alpha;
        }

        public Color(byte red, byte green, byte blue)
        {
            this.red = red;
            this.green = green;
            this.blue = blue;
            this.alpha = 255;
        }

        public byte Red { get; set; }
        public byte Green { get; set; }
        public byte Blue { get; set; }
        public byte Alpha { get; set; }



        public float GreyScale
        {
            get
            {
                return (red + green + blue) / 3.0F;
            }
        }
    }
}

我有一个名为GreyScale的属性,该属性仅将红色,绿色和蓝色字段的平均值返回为浮点数。但是,当我执行以下代码时,第一次调用GreyScale属性后,对可写类成员的后续更改不会再次更改GreyScale的值。

Color color = new Color(255, 255, 255, 255);
Console.WriteLine($"{color.GreyScale}"); // prints 255 as expected
color.Red = 197;
color.Green = 197;
color.Blue = 197;
Console.WriteLine(%"{color.GreyScale}");// should print 197. Prints 255.

2 个答案:

答案 0 :(得分:5)

您对C#自动属性Settings.Builder nodeSettings = Settings.builder() .put("cluster.name", "my-integration-test") .put("http.enabled", "true") .put("path.data", dataDirectory) .put("path.home", "/") .put("transport.type", "netty4") .put("network.host", "_local_") .put("transport.tcp.port", "19200-19400") .put("http.port", "19200-19400") .put("discovery.type", "single-node"); LOG.info("Starting up embedded Elasticsearch"); node = new LocalNode(nodeSettings.build()); 只是syntactic sugar有一个误解,编译器使用getter和setter为公共属性创建私有支持变量。您无需创建专用字节字段,因此不会在代码中使用它们。

{get; set;}

答案 1 :(得分:1)

设置属性using System; namespace HelloWorld { internal class Color { public Color(byte red, byte green, byte blue, byte alpha) { this.Red= red; this.Green = green; this.Blue = blue; this.Alpha= alpha; } public Color(byte red, byte green, byte blue) { this.Red= red; this.Green = green; this.Blue = blue; this.Alpha = 255; } public byte Red { get; set; } public byte Green { get; set; } public byte Blue { get; set; } public byte Alpha { get; set; } public float GreyScale { get { return (this.Red + this.Green + this.Blue) / 3.0F; } } } } RedGreen时,字段Blueredgreen不会被更新。

如果将blue实现为GreyScale,它将起作用,但只有在设置了这些属性之后。

我认为您可能想实现return (Red + Green + Blue)RedGreen的getter和setter来读写支持字段。