为什么在 C# UWP 中为一个内容保留两个变量?
Why keep two variables for one content in C# UWP?
在 C# 中,我注意到许多编码人员会执行以下操作:
class X
{
private int test_;
public int test
{
get { return test_; }
set { if (test_ != value) test_ = value; }
}
}
我的问题是为什么要为相同的内容保留一个私有变量和一个 public 变量?
为什么我们不这样做呢?
class X
{
public int test
{
get; set;
}
}
我的意思是,无论如何我们都在改变私有变量。不使用单个 public 变量有什么意义?
这不是两个变量。一个是字段,另一个是 属性。 属性 是伪装的可选 getter 和 setter 方法。
您提出的解决方案实际上是语言的一部分,称为自动实现的属性:
https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/auto-implemented-properties
代码:
class X
{
public int test
{
get; set;
}
}
...直接等同于此:
class X
{
private int test_;
public int test
{
get { return test_; }
set { test_ = value; }
}
}
第一个示例是自动实现的 属性。 C# 编译器在编译时自动生成第二个示例。
现在,您首先提供的代码有这一行:
set { if (test_ != value) test_ = value; }
您会注意到它做的事情与 auto-属性 等效代码不同。这就是这两种方法的不同之处。
当您为属性使用支持字段时,您可以引入需要代码遵循的特定规则。
例如,您可能想在音乐应用程序上设置音频音量,因此您的代码可能如下所示:
public class Music
{
private int _volume = 7;
public int Volume
{
get { return _volume; }
set
{
if (value >= 0 && value <= 10)
{
_volume = value;
}
}
}
}
当您的 属性 包含这样的逻辑时,通常会有一个私有字段变量。
在 C# 中,我注意到许多编码人员会执行以下操作:
class X
{
private int test_;
public int test
{
get { return test_; }
set { if (test_ != value) test_ = value; }
}
}
我的问题是为什么要为相同的内容保留一个私有变量和一个 public 变量?
为什么我们不这样做呢?
class X
{
public int test
{
get; set;
}
}
我的意思是,无论如何我们都在改变私有变量。不使用单个 public 变量有什么意义?
这不是两个变量。一个是字段,另一个是 属性。 属性 是伪装的可选 getter 和 setter 方法。
您提出的解决方案实际上是语言的一部分,称为自动实现的属性: https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/auto-implemented-properties
代码:
class X
{
public int test
{
get; set;
}
}
...直接等同于此:
class X
{
private int test_;
public int test
{
get { return test_; }
set { test_ = value; }
}
}
第一个示例是自动实现的 属性。 C# 编译器在编译时自动生成第二个示例。
现在,您首先提供的代码有这一行:
set { if (test_ != value) test_ = value; }
您会注意到它做的事情与 auto-属性 等效代码不同。这就是这两种方法的不同之处。
当您为属性使用支持字段时,您可以引入需要代码遵循的特定规则。
例如,您可能想在音乐应用程序上设置音频音量,因此您的代码可能如下所示:
public class Music
{
private int _volume = 7;
public int Volume
{
get { return _volume; }
set
{
if (value >= 0 && value <= 10)
{
_volume = value;
}
}
}
}
当您的 属性 包含这样的逻辑时,通常会有一个私有字段变量。