My official documents in C # using the property to see this code:
public class Date
{
private int _month = 7; // Backing store
public int Month
{
get => _month;
set
{
if ((value > 0) && (value < 13))
{
_month = value;
}
}
}
}
This code where _month
begins with an underscore, used to represent private. What will it do this problem?
- Mixed use project hump nomenclature and underscores nomenclature, disrupting the line of sight to read the code
- Unlike other languages (such as JavaScript), C # itself has provided private modifier, then do not need to underline
_
repeat represents private - Underline
_
has been used to represent abandoned yuan function, is not it confusing?
In fact, I simply use the hump nomenclature, not underlined _
at the beginning, there will not be any problems. code show as below:
public class Date
{
private int month = 7; // Backing store
public int Month
{
get => month;
set
{
if ((value > 0) && (value < 13))
{
month = value;
}
}
}
}
It looks more concise and easier to understand. Here, also from the official document auto-implemented properties in code is very good:
// This class is mutable. Its data can be modified from
// outside the class.
class Customer
{
// Auto-implemented 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;
}
}
In fact, the only hump nomenclature, but do not expose the fields and use the property get / set accessor, or simply played a better variable names, you can always find ways to avoid using the underscore _
at the beginning.