[英]What's the code behind a C# backing field in a auto implemented get; set;?
I am learning it may be something like this: 我正在学习可能是这样的:
public string ModifiedBy {
get { return m_ModifiedBy ?? string.Empty; }
set {
if(value!=null) {
m_ModifiedBy = value;
m_Modified = DateTime.Now;
}
}
}
Is this correct or is there more or less involved? 这是正确的还是涉及或多或少的? I would just like to duplicate exactly what is done with a get; 我只想精确复制get所做的事情; set; 组; that is auto implemented. 这是自动实施的。
It's wrong; 这是不对的; your code is doing much more than just getting and setting a string. 您的代码所做的不只是获取和设置字符串。
An auto-implemented string property ModifiedBy
simply expands to the following equivalent manually-implemented property: 自动实现的字符串属性ModifiedBy
简单地扩展为以下等效的手动实现的属性:
// Key difference: the backing field of an automatic property
// is not accessible by your own code
private string m_modifiedBy;
public string ModifiedBy {
get { return m_modifiedBy; }
set { m_modifiedBy = value; }
}
That's it. 而已。 There is no non-null default of string.Empty
, no other class members are involved, no null checks, no additional logic, etc. Null values are handled in exactly the same way as any other value. 没有string.Empty
非null缺省值,不涉及任何其他类成员,没有null检查,没有其他逻辑,等等。null值的处理方式与任何其他值完全相同。
An auto-implemented property is implemented like this: 自动实现的属性的实现如下:
private int _foo; // compiler-generated
public int Foo
{
get { return _foo; }
set { _foo = value; }
}
The auto-implemented properties will mostly work like in the following example 自动实现的属性将在以下示例中正常工作
// This class is mutable. Its data can be modified from
// outside the class.
class Customer
{
// Auto-Impl Properties for trivial get and set
public double TotalPurchases { get; set; }
public string Name { get; set; }
public int CustomerID { get; set; }
// Constructor
public Customer(double purchases, string name, int ID)
{
TotalPurchases = purchases;
Name = name;
CustomerID = ID;
}
// Methods
public string GetContactInfo() {return "ContactInfo";}
public string GetTransactionHistory() {return "History";}
// .. Additional methods, events, etc.
}
class Program
{
static void Main()
{
// Intialize a new object.
Customer cust1 = new Customer ( 4987.63, "Northwind",90108 );
//Modify a property
cust1.TotalPurchases += 499.99;
}
}
And in your code part you shouldn't check for null
values, because if the null is set to the property then it will not work. 并且在您的代码部分中,您不应检查null
值,因为如果将null设置为该属性,则它将不起作用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.