我有一个奇怪的问题。我试图了解如何正确使用访问器。我想到在类中将它们与私有(private)和公共(public)变量一起使用,但 C# 3.0 允许我们仅将它们与公共(public)变量一起使用(即)
public string Email {get; set;}
所以,我正在编写一个应用程序 - 这是我的代码的一部分:
public class Customers
{
public string Telephone;
public string Email {get; set;}
public void LoadCustomer(string _name)
{
DataSet dataSet = new DataSet();
dataSet.ReadXml("Customers.xml");
XDocument doc = XDocument.Load("Customers.xml");
XElement root = doc.Root;
for (int i = 0; i < dataSet.Tables[0].Rows.Count; i++)
{
var Klient = from wpisy in root.Elements("Customer")
where wpisy.Element("Name").Value.Equals(_name)
select wpisy;
Telephone = Klient.First().Element("Telephone").Value;
Email = Klient.First().Element("Email").Value;
}
}
}
private void Window_Loaded_1(object sender, RoutedEventArgs e)
{
Customers customer = new Customers();
customer.LoadCustomer(name);
txt_Telephone.Text = customer.Telephone;
txt_Email.Text = customer.Email;
}
如您所见,我有一个类和一个在窗口打开时调用该类的方法。每当我使用访问器时一切正常:
public string Email {get; set;}
或者我不:
public string Telephone;
所以,我的问题(可能很愚蠢)是,将访问器与此类公共(public)变量一起使用有什么意义,因为使用与否都没有区别?
最佳答案
两者在功能上没有区别。但是,public string Telephone;
是一个密码,因为它会将您的值及其纯数据公开给外界,而不是通过(隐式)访问器。
这意味着您将永远无法在不破坏现有代码的情况下添加某种验证规则:
private string _email;
public string Email {
get { return _email }
set {
if(value.Contains("@") { _email = value }
}
}
对于外界来说,这仍然用作 MyClass.Email
,但您可以在其背后添加逻辑,如果您只是使用字段而不是属性,这是不可能的。
关于C# 获取设置访问器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19623521/