可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
Sorry If I am being noob, I have this doubt, why do we use private variables and set them using properties ?
Why can't we just use properites alone ?
I am talking about situations like this
private string _testVariable;
public string MyProperty
{
get { return _testVariable;}
set {_testVariable = value;}
}
I am thinking of simply using
public string MyProperty { get; set; }
Why redundant private variable? are these two strategies different ? can anyone please throw some light on this.
Thanks
回答1:
Your examples are semantically the same. The concise property declaration syntax (just having { get; set; }
) is a shortcut available in C# 3.0. The compiler actually creates a private backing variable and a simple getter and setter as in your first example.
If all you're doing is creating a getter and setter (and nothing actually happens when either occurs), then the concise syntax is a good option. If you have to perform any other actions (redraw a control, for example) when you set the value, then the full syntax is required.
回答2:
Why redundant private variable? are
these two strategies different ? can
anyone please throw some light on
this.
If all your doing is reading/writing a variable, then no. Otherwise, there's two reasons why you'd want a private variable:
Data validation
// Data validation
public class IntWrapper
{
private int _value;
public int Value
{
get { return _value; }
set
{
if (value < 0) { throw new Exception("Value must be >= 0"); }
_value = value;
}
}
}
Getter/setter wraps up an underlying data store
public class StringBuffer
{
List<char> chars = new List<char>();
// Wraps up an underlying data store
public string Value
{
get { return new String(chars.ToArray()); }
set { chars = new List<char>(value.ToCharArray()); }
}
public void Write(string s) { Write(chars.Count, s); }
public void Write(int index, string s)
{
if (index > chars.Count) { throw new Exception("Out of Range"); }
foreach(char c in s)
{
if (index < chars.Count) { chars[index] = c; }
else { chars.Add(c); }
index++;
}
}
}
回答3:
The second example that you give:
public string MyProperty { get; set; }
Is only available in later versions of the .Net framework (v3.0 onwards I believe)
The first example allows you to set breakpoints on the return
and assignment statements, causing your debugger to break when the property is assigned / read.
回答4:
The 1st code snip allws you to modify some private class state. Wrapping private state in a property is nice because it hides the implementation. Later you can change the implementation and the property (external interface) may remain unchanged.
For example, suppose instead of setting a single string within the setter, you set the string in a private store of some sort. You write it to a file, or write it to shared memory. Or maybe you compute the hash of the string only, and don't store it at all, as you might do with a password.
The auto properties in your 2nd code snip are not related to the private variable at all. The auto-property design, like the explicit property design used in the first snip, allows future modification. As part of that modification, for example, you could convert from auto properties to explicitly implemented properties.
回答5:
Mashesh,
We all had to start somewhere! You asked about private vars vs properties with this ex:
private string _testVariable;
public string MyProperty
{
get { return _testVariable;}
set {_testVariable = value;}
}
-or-
public string MyProperty { get; set; }
Did you consider:
public string MyProperty { get; private set; }
You can apply scope to property getters/setters . . . . cool stuff. Oh yeah . . . when using this type of property within the defining class (like in a constructor) prepend it with a 'this.' - so an assignment would look like 'this.MyProperty = "An Assigned String";'. This makes your intentions much more clear . . .
回答6:
Property is basically the wrapper around a field. This wrapper enables to use the variable from outside world. In C#3.0 you can simply declare a property like public string MyProperty { get; set; }
The compiler declares a private variable automatically and get set methods for that also. If you need to perform any calculation inside the class that is declaring the property, then you should use the private field for that.
回答7:
Sometimes you don't know when you first write the code whether you may be adding some more code later that needs to use the private variable. Sure, you can add it later if needed. I just automatically create the private variable, assuming that it will be used later.
This may be more relevant in large enterprise apps or rapidly evolving apps (agile) where the full implementation may not be known during the initial coding.
回答8:
I HATE backing variables when they are not needed it is causes more complexity then necessary.
Obviously if you have the need to do something special in the getter or setter then the full semantic form should be used and not the sugar.
Also I like to use properties as a method of debugging how the property gets set or gets used sometimes this isn't as obvious because of reflection and that is one reason I like to use them.
I find it frustrating trying to debug code when there is a possibility that the backing variable maybe accessed either internally in the class by the property it self or the backing variable and nothing tells the coder the right way to access.
You can access the backing variable internally as well as the property so which is the right way? It is not obvious...
回答9:
This isnt related to C# the langugage, but more the application.
One reason to use properties, is that its treated as "Special" in many frameworks.
For example, Silverlight and WPF will bind to properties and not to fields