我在C#中编写getter setter,我可以用样式或语法编写,是什么时候使用其中一个?封装是从它们两者实现的吗?
示例1:
public List<ChatMessage> MessageListWithoutPrivateVariable { get; set; }
示例2:
public List<ChatMessage> MessageList {
set {
messageCollection = value;
} get {
return messageCollection;
}
}
答案 0 :(得分:5)
一般来说,两种方式都是一样的。在C#v3.0之前,第一种可能性不适合程序员。但微软认为如果程序员可以像你先描述的那样编写速记风格会更有效率。
所以实际上它只是缩写形式,也称为自动实现的属性。 C#在后台自动生成一个后备字段,因此允许封装。
在某些情况下,您将需要第二种方法,也称为手动属性。例如,如果您想在setter中使用INotifyPropertyChanged或其他一些值检查。
回答你的问题:用你喜欢的。或者如果可能的话,先使用第一种方法
答案 1 :(得分:0)
如您所见,如果您运行以下代码,编译器会为变量免费版本生成一个私有变量。
using System;
using System.Reflection;
namespace SO40415991
{
class MyClass
{
public int MyFirstValue { get; set; }
private int m_mySecondValue;
public int MySecondValue
{
get { return m_mySecondValue; }
set
{
m_mySecondValue = value;
}
}
}
class Program
{
static void Main(string[] args)
{
FieldInfo[] fis = typeof(MyClass).GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);
foreach (var fi in fis)
{
Console.WriteLine($"{ fi.Name} {fi.IsPrivate}");
}
Console.WriteLine();
Console.WriteLine("END");
Console.ReadLine();
}
}
}
除非你想在你的内部使用它,否则不需要显式的私有变量(字段的访问速度比属性稍快)。
答案 2 :(得分:0)
Example 1
是Example 2
中引入的C# 3.0
的简写语法。如果您使用C# 2.0
进行编码,则应使用Example 2
,但在3.0
之后,您可以使用Example 1
中的速记版本。
无论如何,如果你需要进行一些操作(或)计算,你可以在3.0之后使用Example 2
,如下所示。
private List<ChatMessage> messageCollection;
public List<ChatMessage> MessageList {
set {
messageCollection = value;
} get {
if(messageCollection == null) {
return new List<ChatMessage>();
} else {
return messageCollection;
}
}
}
答案 3 :(得分:0)
{get;组;被称为“自动属性”,本质上是一个简写(你的“例子2”) 当你写{get;组; - 编译器将生成类似的代码(如例2)。
答案 4 :(得分:0)
两者都相同但不同。
只要您没有提供额外的定义,两种表示都会表现出来 同样,如下所示
public int weight { get; set; }
private int _weight;
public int weight
{
get { return _weight;}
set { _weight = value;}
}
但是,让我们考虑另一种情况,如果重量&gt; 40,你想要定义不同的东西。它可以修改后备字段_weight,也可以更改其他私有变量(_charge)。
public int weight
{
get { return _weight; }
set
{
_weight = value;
if (_weight > 40)
_charge = _weight * 2;
else
_charge = _weight * 1;
}
}
private int _charge;
public int Charge
{
get { return _charge; }
set { _charge = value; }
}
如果你想像上面那样在你的财产上应用一些业务逻辑,那就会产生很大的不同。