C#-简单属性使用示例表单教程不';行不通
作为C#的初学者,我正在网上寻找有用的教程。我遇到了这个:。我发现了一个假设很简单的例子,说明属性使用会产生意想不到的结果(我使用的是Microsoft Visual Studio 2015)。该示例取自第一课和上一课C#-简单属性使用示例表单教程不';行不通,c#,properties,C#,Properties,作为C#的初学者,我正在网上寻找有用的教程。我遇到了这个:。我发现了一个假设很简单的例子,说明属性使用会产生意想不到的结果(我使用的是Microsoft Visual Studio 2015)。该示例取自第一课和上一课 using System; namespace Workshop { class Program { static void Main(string[] args) { Car car;
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方法中。
在代码中,您没有调用颜色的set方法。
如果需要此行,请编辑构造函数:
public Car(string color)
{
this.Color = color;
}
但是,当字符串不是“红色”时,不设置颜色。因此,输出将是:
The car is RED
This car can only be red!
然后,您将得到一个NullReferenceException,因为color
在return color.ToUpper()中为null代码>该行处于Color
属性的设置方法中。
在代码中,您没有调用颜色的set方法。
如果需要此行,请编辑构造函数:
public Car(string color)
{
this.Color = color;
}
但是,当字符串不是“红色”时,不设置颜色。因此,输出将是:
The car is RED
This car can only be red!
然后,您将得到一个NullReferenceException,因为color
在return color.ToUpper()中为null代码>该行处于Color
属性的设置方法中。
在代码中,您没有调用颜色的set方法。
如果需要此行,请编辑构造函数:
public Car(string color)
{
this.Color = color;
}
但是,当字符串不是“红色”时,不设置颜色。因此,输出将是:
The car is RED
This car can only be red!
然后,您将得到一个NullReferenceException,因为color
在return color.ToUpper()中为null代码>该行处于Color
属性的设置方法中。
在代码中,您没有调用颜色的set方法。
如果需要此行,请编辑构造函数:
public Car(string color)
{
this.Color = color;
}
但是,当字符串不是“红色”时,不设置颜色。因此,输出将是:
The car is RED
This car can only be red!
然后,您将得到一个NullReferenceException,因为color
在return color.ToUpper()中为null
您已经在构造函数中设置了color
(变量),因此没有发生任何验证,因为您已经将验证放置在color
(属性)的set{}
中。
因此,由于您没有设置Color
,因此它不会命中setter。您在构造函数中设置了Color
(变量),因此没有发生验证,因为您将验证放置在Color
(属性)的集合{}
。
因此,由于您没有设置Color
,因此它不会命中setter。您在构造函数中设置了Color
(变量),因此没有发生验证,因为您将验证放置在Color
(属性)的集合{}
。
因此,由于您没有设置Color
,因此它不会命中setter。您在构造函数中设置了Color
(变量),因此没有发生验证,因为您将验证放置在Color
(属性)的集合{}
。
因此,由于您没有设置颜色
,因此它不会命中setter。第二行在属性的set方法中。因此,它将输出仅当您设置颜色(除红色以外的任何颜色)时,此车才能为红色。您从未从属性中设置字段,请尝试This.color=color
第二行在属性的设置方法中。因此,它将输出仅当您设置颜色(除红色以外的任何颜色)时,此车才能为红色。您从未从属性中设置字段,请尝试This.color=color
第二行在属性的设置方法中。因此,它将输出仅当您设置颜色(除红色以外的任何颜色)时,此车才能为红色。您从未从属性中设置字段,请尝试This.color=color
第二行在属性的设置方法中。因此,它将输出仅当您设置颜色(除红色以外的任何颜色)时,此车才能为红色。如果您从未从属性中设置字段,请尝试This.color=color