private string myName;
public string MyName;// this is a property, speical to c#, which sets the backing field.
private string myName = "mary";// the backing field.
public string MyName // this is a property, which sets/gets the backing field.
{
get
{
return myName;
}
set< br /> {
if (value != "Silly Woman"){
myName = value;
}
}
}
But I have been looking at the code in c# that looks like this:
public string MyName {get; set; }
Why are you just Get a get-set with nothing there, – isn’t it just exposing your private support area? If you can get it from the outside and set it up, why not do it directly?
< /p>
public string Name {get; set; }
Same as building attributes supported by fields:
private string _name;< br />public string Name {
get {return _name; }
set {_name = value; }
}
The point of these attributes is not to hide data. Just like you Observed, they don’t do this. Instead, these attributes can perform other operations, not just use fields:
public string Name {
get {return _name; }
set {if (value == null) throw new Exception("GTFO!"); _name = value; }
}
The other thing is , You can make the attribute virtual:
public virtual string Name {get; set; }
If it is overridden, you can provide a different The results and behavior.
Newbie to C#, I know that encapsulation is just a way of “protecting data”. But I still don’t know. I think get and set accessors The point is to add tests in these methods to check whether the parameters meet certain conditions, and then allow external functions to get and set anything, as shown below:
private string myName;
public string MyName;// this is a property, speical to c#, which sets the backing field.
private string myName = "mary";// the backing field.
public string MyName // this is a property, which sets/gets the backing field.
{
get
{
return myName;
}
set
{
if (value != "Silly Woman"){
myName = value;
}
}
}
But I have been looking at the code in c# that looks like this:
public string MyName {get; set; }
Why are you just there Get a get-set without anything,-isn’t this more than just exposing your private support area? If you can get it from the outside and set it up, why not do it directly?
In fact, create an automatic attribute as follows:
public string Name {get; set; }
Same as building attributes supported by fields:
private string _name;
public string Name {
get {return _name; }
set {_name = value; }
}
The point of these attributes is not to hide data. As you have observed, they don’t do this. On the contrary , These attributes can perform other operations, not just use fields:
public string Name {
get {return _name; }
set {if (value == null) throw new Exception("GTFO!"); _name = value; }
}
Another thing is that you can make attributes virtual:
< p>
public virtual string Name {get; set; }
If it is overridden, different results and behaviors can be provided in the derived class.