Why use the 'ref' keyword when passing an object?

后端 未结 11 1537
被撕碎了的回忆
被撕碎了的回忆 2020-11-22 06:45

If I am passing an object to a method, why should I use the ref keyword? Isn\'t this the default behaviour anyway?

For example:

class Program
{
    s         


        
11条回答
  •  孤独总比滥情好
    2020-11-22 07:41

    Think of variables (e.g. foo) of reference types (e.g. List) as holding object identifiers of the form "Object #24601". Suppose the statement foo = new List {1,5,7,9}; causes foo to hold "Object #24601" (a list with four items). Then calling foo.Length will ask Object #24601 for its length, and it will respond 4, so foo.Length will equal 4.

    If foo is passed to a method without using ref, that method might make changes to Object #24601. As a consequence of such changes, foo.Length might no longer equal 4. The method itself, however, will be unable to change foo, which will continue to hold "Object #24601".

    Passing foo as a ref parameter will allow the called method to make changes not just to Object #24601, but also to foo itself. The method might create a new Object #8675309 and store a reference to that in foo. If it does so, foo would no longer hold "Object #24601", but instead "Object #8675309".

    In practice, reference-type variables don't hold strings of the form "Object #8675309"; they don't even hold anything that can meaningfully converted into a number. Even though each reference-type variable will hold some bit pattern, there is no fixed relationship between the bit patterns stored in such variables and the objects they identify. There is no way code could extract information from an object or a reference to it, and later determine whether another reference identified the same object, unless the code either held or knew of a reference that identified the original object.

提交回复
热议问题