PDA

View Full Version : get و Set



Mahbadgroup
پنج شنبه 06 دی 1386, 09:43 صبح
سلام خسته نباشید . میخوام بدنم دقیقا چه زمانی از get وSet باید استفاده کرد ؟؟ و کجاها نباید استفاده کرد؟؟ یعنی می خوام بدونم میشه به جای هر تابعی از get , set استفاده کنیم و فرق آن با تایع در چیست.؟؟؟؟؟

سار
پنج شنبه 06 دی 1386, 09:48 صبح
http://www.java2s.com/Code/CSharp/Language-Basics/Usepropertiestosetandgetprivatemembers.htm

hassan razavi
پنج شنبه 06 دی 1386, 09:51 صبح
set و get برای پیاده سازی Propertise ها هستند. set در هنگام مقداردهی به Propertise فراخوانی می شود و Get در هنگام خواندن مقدار Properties فراخوانی میشود.
می توان هردو و یا هر یک را بکار برد. اگر فقط Get پیاده سازی شود (Read Only) اگه فقط Set پیاده سازی شود (Write Only) نامند آنرا.

sinpin
پنج شنبه 06 دی 1386, 10:20 صبح
سلام خسته نباشید . میخوام بدنم دقیقا چه زمانی از get وSet باید استفاده کرد ؟؟ و کجاها نباید استفاده کرد؟؟ یعنی می خوام بدونم میشه به جای هر تابعی از get , set استفاده کنیم و فرق آن با تایع در چیست.؟؟؟؟؟

بنقل از : http://msdn2.microsoft.com/en-us/library/bzwdh01d(VS.71).aspx (http://msdn2.microsoft.com/en-us/library/bzwdh01d%28VS.71%29.aspx)

Properties vs. Methods

Class library designers often must decide between implementing a class member as a property or a method. In general, methods represent actions and properties represent data. Use the following guidelines to help you choose between these options.
Use a property when the member is a logical data member. In the following member declarations,Use a method when:
The operation is a conversion, such as Object.ToString.
The operation is expensive enough that you want to communicate to the user that they should consider caching the result.
Obtaining a property value using the get accessor would have an observable side effect.
Calling the member twice in succession produces different results.
The order of execution is important. Note that a type's properties should be able to be set and retrieved in any order.
The member is static but returns a value that can be changed.
The member returns an array. Properties that return arrays can be very misleading. Usually it is necessary to return a copy of the internal array so that the user cannot change internal state. This, coupled with the fact that a user can easily assume it is an indexed property, leads to inefficient code. In the following code example, each call to theبنقل از : http://srtsolutions.com/blogs/billwagner/archive/2006/09/04/properties-vs-methods.aspx (http://srtsolutions.com/blogs/billwagner/archive/2006/09/04/properties-vs-methods.aspx)

My first answer:

There are a few reasons why I believe Properties are beneficial vs. the traditional get and set methods used in earlier OO languages (such as C++).
Consider SOA and a document centric API:

Properties are naturally serialized using the XML serializer. Therefore, a list of employees defined using properties becomes a simple XML document for wire transfer. (I’m assuming read/write properties for Name, Salary, etc). You can’t easily use the XML serialize for a similar type implement using get / set methods. This is a necessity to build SOA applications where the client will request a document from the server. The natural document is the set of public properties for a data type. (The same argument can be made for the client code, where a command document is a type with a set of public properties).
Databinding:

This one may be cheating, because one could argue that MS could implement databinding using get / set methods. But they didn’t, so properties are the clear winner here. And, in fact, if MS did use a get / set metaphor, it would be similar to Java beans, where get_ and set_ denoted a property. Personally, I dislike the idea that a methods name can give it magical behavior.
Clarity:

Despite the text in the article you reference below, I think there is merit to the property syntax, when used correctly. It clearly shows that a type contains certain data elements (at least logically, even if not physically). Point.X looks cleaner to me than Point.get_X(), or Point.set_X(256). The syntax of the language expresses the design intent more clearly. That’s certainly subjective, but that’s my opinion.
To address your concern below, there are two answers. First, it’s much less likely to make the mistake of if (obj.ServerDown = false) because it can only be done with boolean types (not any arbitrary integral type as in C or C++). Secondly, the habit of putting the constant on the left side fixes that as well: if (false == obj.ServerDown).
On the question of hiding inefficiencies behind properties:

Let's consider this code:

public void Calc(int[] foo)
{
Sum = 0;
for (int i = 0; i < foo.Length; i++)
Sum += foo[i];
}
It is indeed possible that the Length property (or the indexer) cause serious inefficiencies. (Look at the code again, and imagine that Sum is a property with Get and Set accessors.) But, let's not get carried away. In most cases, the JIT compiler will inline simple properties, and there is no inefficiency at all. Of course, you may consider caching the temp variable anyway, and there may be some savings, if the setter has extensive validation.
Syntactically, you could hide anything inside a property's get or set methods. You could even include database access to retrieve (or set) the value. But, just because it's syntactically correct doesn't mean you should do it. I’d say it’s a bad practice to hide a database access behind a property for several reasons. Would you ever make a database call to retrieve one scalar value? (That’s what such a getter would look like.) Wouldn’t it be far more likely that you would design your application to pull some reasonable set of data from the database and have it locally available? My point is that I wouldn’t believe GetCommission() makes a database call any more than a SalesPerson.Commission property. And, if the app really does use some form of lazy evaluation, you’re paying the performance hit regardless of the property or method syntax, so it really doesn’t matter.
So, if the argument is that properties are ‘hiding’ performance issues, I don’t think that’s often true. Most developers would think getSomething() and setSomething() would contain the same code as a Something property. The JIT compiler knows a property is a get / set method pair and can perform the same optimizations as a get / set method pair. So, you really don’t lose anything. In some sense, properties are syntactic sugar (there’s no new amazing functionality here), but the XML Document serialization and databinding are the two practical reasons to prefer them over get / set methods. Your colleagues have found the one negative (= vs. ==), which has been around since the dawn of C, so we’ve probably got the habits to handle that one.
After that initial dialogue, the reader and I discussed some guidelines for deciding between properties and methods. Because, there are performance pitfalls hiding behind properties and indexers, if misused.
Here's what we came up with:
Use a Property when all these are true:
The getters should be simple and thus unlikely to throw exceptions. Note that this implies no network (or database) access. Either might fail, and therefore would throw an exception.
They should not have dependencies on each other. Note that this would include setting one property and having it affect another. (For example, setting the FirstName property would affect a read-only FullName property that composed the first name + last name properties implies such a dependency )
They should be settable in any order
The getter does not have an observable side effect Note this guideline doesn't preclude some forms of lazy evaluation in a property.
The method must always return immediately. (Note that this precludes a property that makes a database access call, web service call, or other similar operation).
Use a method if the member returns an array.
Repeated calls to the getter (without intervening code) should return the same value.
Repeated calls to the setter (with the same value) should yield no difference from a single call.
The get should not return a reference to internal data structures (See item 23). A method could return a deep copy, and could avoid this issue.

صنم2010
سه شنبه 19 اردیبهشت 1391, 20:59 عصر
می شه بپرسم که دلیل استفاده کرده get و set دقیقا چیه ؟
ممنون

amirxbest
سه شنبه 19 اردیبهشت 1391, 22:06 عصر
تا اونجایی که من خوندمخ و میدونم.واسه اینه که طبق قوانین شئُ گرایی عمل کنیم و کد استاانداردی داشته باشیم.
مثلا شما تو کلاس یه متغیر خصوصی(private)تعریف میکنی که از بیرون از کلاس قابل دسترسی نباشه.(تعین سطح دسترسی)
بعد از این طریق تنظیم کنی مقداری رو یا استفاده کنی...
موفق باشید.