代码之家  ›  专栏  ›  技术社区  ›  Mutating Algorithm

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

c#
  •  0
  • Mutating Algorithm  · 技术社区  · 6 年前

    我有一个非常简单的问题 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 回复  |  直到 6 年前
        1
  •  5
  •   Brian Ogden    6 年前

    你只是误解了C#auto的财产 {get; set;} 这只是 syntactic sugar ,编译器使用getter和setter为公共属性创建私有支持变量。您不需要创建专用字节字段,因此在代码中不会使用它们。

    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;
                }
            }
        }
    }
    
        2
  •  1
  •   Jay    6 年前

    Red , Green Blue ,田野 red , green blue 没有被更新。

    GreyScale 实施的目的是: return (Red + Green + Blue)

    我认为您可能想要为实现getter和setter 红色 绿色