A property, indexer or dynamic member access may not be passed as an out or ref parameter [duplicate]
Hello I'm having trouble figuring this out. I have these structs and classes.
struct Circle
{ ... }
class Painting
{
List<Circle> circles;
public List<Circle> circles
{
get { return circles; }
}
}
I am trying to modify one of the circles inside the painting class from outside it, using this code:
MutatePosition(ref painting.Circles[mutationIndex], painting.Width, painting.Height);
This line is giving me a compiler error:
A property, indexer or dynamic member access may not be passed as an out or ref parameter
Why is this, and what can I do to solve it without changing my code too much?
The error is pretty clear - you can't pass a property to a ref parameter of a method.
You need to make a temporary:
var circle = painting.Circles[mutationIndex];
MutatePosition(ref circle, painting.Width, painting.Height);
painting.Circles[mutationIndex] = circle;
That being said, mutable structs are often a bad idea. You might want to consider making this a class instead of a struct.
If there's only one ref param and no return type for MutatePosition you can return the value.
painting.Circles[mutationIndex] = MutatePosition(circle, painting.Width, painting.Height);
If there are multiple ref params and/or already a return type you can create a new type that includes everything that needs to be returned.
class MutateResults() { Circle Circle; object OtherReffedStuff; }
精彩评论