C# - 简单 属性 用法示例表单教程不起作用

C# - simple property usage example form tutorial doesn't work

作为 C# 的初学者,我正在互联网上寻找有用的教程。我遇到了这个:http://csharp.net-tutorials.com/ . I found supposedly easy example of property usage that gives unexpected result (I'm using Microsoft Visual Studio 2015). The example is taken from lesson http://csharp.net-tutorials.com/classes/properties/ 和上一课。

using System;
namespace Workshop
{

    class Program
    {
        static void Main(string[] args)
        {
            Car car;

            car = new Car("Red");
            Console.WriteLine(car.Describe());

            car = new Car("Green");
            Console.WriteLine(car.Describe());

            Console.ReadLine();

        }
    }

    class Car
    {
        private string color;

        public Car(string color)
        {
            this.color = color;
        }

        public string Describe()
        {
            return "This car is " + Color;
        }

    public string Color
    {
        get
        {
            return color.ToUpper();
        }
        set
        {
            if (value == "Red")
                color = value;
            else
                Console.WriteLine("This car can only be red!");
        }
    }
}

这个程序的结果是:

The car is RED
The car is GREEN

虽然我预计第二行是:

This car can only be red!

谁能给我解释一下为什么这个例子会这样? 还有更一般的问题:有人知道这个教程是否不错,或者我应该寻找不同的东西吗?

该行在Color属性的set方法中。 在您的代码中,您没有调用 Color 的 set 方法。 如果你想要这一行,编辑你的构造函数:

public Car(string color)
{
   this.Color = color;
}

但是,当字符串不是 "Red" 时,您不设置 color。所以,输出将是:

The car is RED
This car can only be red!

之后,您将得到一个 NullReferenceException,因为 colorreturn color.ToUpper();

中为 null

您在构造函数中设置了 color(变量),因此没有发生验证,因为您将验证放在 Color(属性) 的 set{} 中。 所以因为你没有设置 Color,它永远不会达到 setter。