This question already has an answer 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 6 answers
C#属性和ref参数,为什么没糖? 9个答案
属性或索引器可能不会作为out或ref参数6回答传递
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
属性,索引器或动态成员访问不能作为out或ref参数传递
Why is this, and what can I do to solve it without changing my code too much?
为什么这样,如果不过多地改变我的代码,我该怎么做才能解决它?
2 个解决方案
#1
33
The error is pretty clear - you can't pass a property to a ref parameter of a method.
错误很明显 - 您无法将属性传递给方法的ref参数。
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.
话虽如此,可变结构往往是一个坏主意。您可能想要考虑将其设为类而不是结构。
#2
2
If there's only one ref param and no return type for MutatePosition you can return the value.
如果MutatePosition只有一个ref参数且没有返回类型,则可以返回该值。
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.
如果有多个ref参数和/或已经是返回类型,则可以创建一个包含需要返回的所有内容的新类型。
class MutateResults() { Circle Circle; object OtherReffedStuff; }
#1
33
The error is pretty clear - you can't pass a property to a ref parameter of a method.
错误很明显 - 您无法将属性传递给方法的ref参数。
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.
话虽如此,可变结构往往是一个坏主意。您可能想要考虑将其设为类而不是结构。
#2
2
If there's only one ref param and no return type for MutatePosition you can return the value.
如果MutatePosition只有一个ref参数且没有返回类型,则可以返回该值。
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.
如果有多个ref参数和/或已经是返回类型,则可以创建一个包含需要返回的所有内容的新类型。
class MutateResults() { Circle Circle; object OtherReffedStuff; }