Suppose we have a function MutateX
which will mutate a mutable object x
(in my case a byte[]), which unsurprisingly c开发者_运维知识库hanges x
's state. I can define MutateX
in two ways
void MutateX (ref Object x); // (A)
// or
void MutateX (Object x); // (B)
X being a reference value anyway - either will work although.
To me ref
indicates that the function is going to change x
in some way (whether or not it changes the actual reference value to some other Object). Is there one form preferred over the other?
I notice that in SerialPort.Read is implemented without
If you are only changing the state of the object (i.e. not reassigning the reference, but setting properties / calling methods / etc), then no: don't use ref
.
To me ref indicates that the function is going to change x in some way
Indeed it does! But you aren't changing x
- you are changing to object referred to by x
, which is a different thing.
Use ref
if:
- changing the reference itself (for reference-types)
- changing the state of a value-type (yuck, should be immutable, or use the return value of the method, which may be simpler)
So in short; "no". Actually, ref
is pretty uncommon and poorly understood, which is another reason to minimise use of it unless necessary.
ref
should be used only when you change the parameter itself - in this case, x itself, not the contents of x.
Code is to be read and understood., do not use keywords for other purposes than they are intended to. You'd confuse everyone else who reads your code - and that might include you in five years. It's not even a case of preference, it's simply wrong, wrong, wrong.
What you are looking for is actually const
- which isn't implemented in .NET, partly because (as every C++ programmer can tell you) it's an incomplete and tricky beast.
If you DO think this is important, you could use your own nomenclature consistently, and document it with the project rules, e.g.
void UseX(Object constX) { ... }
void MutateX(Object x) { ... }
No - if you only need to modify properties of or the contents of the object passed, you don't need ref. An object instance of a class is passed as a reference anyway - you can totally change it inside your code.
You need ref when you want to actually instantiate the object inside your method - in that case, you're not modifying a property of the object passed in, you're actually modifying the object itself (its instance, by creating it).
精彩评论