开发者

A property, indexer or dynamic member access may not be passed as an out or ref parameter [duplicate]

This question already has 开发者_如何学Goanswers here: C# property and ref parameter, why no sugar? (9 answers) A property or indexer may not be passed as an out or ref parameter (9 answers) Closed 9 years ago.

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; }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜