错误:“无法修改返回值”c#
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1747654/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Error: "Cannot modify the return value" c#
提问by P a u l
I'm using auto-implemented properties. I guess the fastest way to fix following is to declare my own backing variable?
我正在使用自动实现的属性。我想解决以下问题的最快方法是声明我自己的支持变量?
public Point Origin { get; set; }
Origin.X = 10; // fails with CS1612
Error Message: Cannot modify the return value of 'expression' because it is not a variable
An attempt was made to modify a value type that was the result of an intermediate expression. Because the value is not persisted, the value will be unchanged.
To resolve this error, store the result of the expression in an intermediate value, or use a reference type for the intermediate expression.
错误消息:无法修改“表达式”的返回值,因为它不是变量
试图修改作为中间表达式结果的值类型。因为该值不是持久化的,所以该值将保持不变。
要解决此错误,请将表达式的结果存储在中间值中,或对中间表达式使用引用类型。
采纳答案by Greg Beech
This is because Point
is a value type (struct
).
这是因为Point
是值类型 ( struct
)。
Because of this, when you access the Origin
property you're accessing a copyof the value held by the class, not the value itself as you would with a reference type (class
), so if you set the X
property on it then you're setting the property on the copy and then discarding it, leaving the original value unchanged. This probably isn't what you intended, which is why the compiler is warning you about it.
因此,当您访问该Origin
属性时,您正在访问该类持有的值的副本,而不是像使用引用类型 ( class
) 那样访问该值本身,因此,如果您X
在其上设置了该属性,那么您正在设置副本上的属性,然后丢弃它,保持原始值不变。这可能不是您想要的,这就是编译器警告您的原因。
If you want to change just the X
value, you need to do something like this:
如果只想更改X
值,则需要执行以下操作:
Origin = new Point(10, Origin.Y);
回答by AnthonyWJones
Using a backing variable won't help.The Point
type is a Value type.
使用支持变量无济于事。的Point
类型是数值类型。
You need to assign the whole Point value to the Origin property:-
您需要将整个 Point 值分配给 Origin 属性:-
Origin = new Point(10, Origin.Y);
The problem is that when you access the Origin property what is returned by the get
is a copy of the Point structure in the Origin properties auto-created field. Hence your modification of the X field this copy would not affect the underlying field. The compiler detects this and gives you an error since this operation is entirely useless.
问题在于,当您访问 Origin 属性时,返回的get
是 Origin 属性自动创建字段中 Point 结构的副本。因此,您对该副本的 X 字段的修改不会影响基础字段。编译器检测到这一点并给你一个错误,因为这个操作完全没用。
Even if you used your own backing variable your get
would look like:-
即使您使用自己的后备变量,您的get
外观也会像:-
get { return myOrigin; }
You'd still be returning a copy of the Point structure and you'd get the same error.
您仍然会返回 Point 结构的副本,并且会遇到相同的错误。
Hmm... having read your question more carefully perhaps you actually mean to modify the backing variable directly from within your class:-
嗯...更仔细地阅读了您的问题,也许您实际上是想直接从您的班级中修改后备变量:-
myOrigin.X = 10;
Yes that would be what you would need.
是的,这就是你需要的。
回答by MSIL
I guess the catch here is that you are trying to assign object's sub-values in the statement rather than assigning the object itself. You need to assign the entire Point object in this case as the property type is Point.
我想这里的问题是您试图在语句中分配对象的子值,而不是分配对象本身。在这种情况下,您需要分配整个 Point 对象,因为属性类型是 Point。
Point newOrigin = new Point(10, 10);
Origin = newOrigin;
Hope I made sense there
希望我在那里说得通
回答by Fredrik Normén
The problem is that you point to a value located on the stack and the value will not be relfected back to the orignal property so C# does not allow you to return a reference to a value type. I think you can solve this by removing the Origin property and instead use a public filed, yes I know it's not a nice solution. The other solution is to not use the Point, and instead create your own Point type as an object.
问题是您指向位于堆栈上的值,并且该值不会返回到原始属性,因此 C# 不允许您返回对值类型的引用。我认为你可以通过删除 Origin 属性来解决这个问题,而是使用公共文件,是的,我知道这不是一个很好的解决方案。另一种解决方案是不使用 Point,而是创建您自己的 Point 类型作为对象。
回答by nawfal
By now you already know what the source of the error is. In case a constructor doesn't exist with an overload to take your property (in this case X
), you can use the object initializer (which will do all the magic behind the scenes). Not that you need not make your structs immutable, but just giving additional info:
到现在为止,您已经知道错误的根源是什么。如果不存在带有重载的构造函数来获取您的属性(在本例中X
),您可以使用对象初始值设定项(它将在幕后完成所有魔术)。并不是说您不需要使您的结构不可变,而只是提供附加信息:
struct Point
{
public int X { get; set; }
public int Y { get; set; }
}
class MyClass
{
public Point Origin { get; set; }
}
MyClass c = new MyClass();
c.Origin.X = 23; //fails.
//but you could do:
c.Origin = new Point { X = 23, Y = c.Origin.Y }; //though you are invoking default constructor
//instead of
c.Origin = new Point(23, c.Origin.Y); //in case there is no constructor like this.
This is possible because behind the scenes this happens:
这是可能的,因为在幕后发生了这种情况:
Point tmp = new Point();
tmp.X = 23;
tmp.Y = Origin.Y;
c.Origin = tmp;
This looks like a very odd thing to do, not at all recommended. Just listing an alternate way. The better way to do is make struct immutable and provide a proper constructor.
这看起来很奇怪,完全不推荐。只是列出另一种方式。更好的方法是使 struct 不可变并提供适当的构造函数。
回答by Mitselplik
Aside from debating the pros and cons of structs versus classes, I tend to look at the goal and approach the problem from that perspective.
除了争论结构体与类的优缺点之外,我倾向于从这个角度看待目标并解决问题。
That being said, if you don't need to write code behind the property get and set methods (as in your example), then would it not be easier to simply declare the Origin
as a field of the class rather than a property? I should think this would allow you to accomplish your goal.
话虽如此,如果您不需要在属性 get 和 set 方法后面编写代码(如您的示例中所示),那么简单地将 the 声明Origin
为类的字段而不是属性会不会更容易?我应该认为这会让你实现你的目标。
struct Point
{
public int X { get; set; }
public int Y { get; set; }
}
class MyClass
{
public Point Origin;
}
MyClass c = new MyClass();
c.Origin.X = 23; // No error. Sets X just fine
回答by Roberto Mutti
Just remove the property "get set" as follow, and then everything works as always.
只需删除属性“get set”如下,然后一切照常工作。
In case of primitive types instread use the get;set;...
如果原始类型 instread 使用 get;set;...
using Microsoft.Xna.Framework;
using System;
namespace DL
{
[Serializable()]
public class CameraProperty
{
#region [READONLY PROPERTIES]
public static readonly string CameraPropertyVersion = "v1.00";
#endregion [READONLY PROPERTIES]
/// <summary>
/// CONSTRUCTOR
/// </summary>
public CameraProperty() {
// INIT
Scrolling = 0f;
CameraPos = new Vector2(0f, 0f);
}
#region [PROPERTIES]
/// <summary>
/// Scrolling
/// </summary>
public float Scrolling { get; set; }
/// <summary>
/// Position of the camera
/// </summary>
public Vector2 CameraPos;
// instead of: public Vector2 CameraPos { get; set; }
#endregion [PROPERTIES]
}
}
回答by Matt
I think a lot of people are getting confused here, this particular issue is related to understanding that value type propertiesreturn a copy of the value type (as with methods and indexers), and value type fieldsare accessed directly. The following code does exactly what you are trying to achieve by accessing the property's backing field directly (note: expressing a property in its verbose form with a backing field is the equivalent of an auto property, but has the advantage that in our code we can access the backing field directly):
我认为很多人在这里感到困惑,这个特殊问题与理解值类型属性返回值类型的副本(与方法和索引器一样)以及直接访问值类型字段有关。以下代码通过直接访问属性的支持字段来完成您想要实现的目标(注意:使用支持字段以详细形式表达属性相当于自动属性,但其优点是在我们的代码中我们可以直接访问支持字段):
class Program
{
static void Main(string[] args)
{
var myClass = new MyClass();
myClass.SetOrigin();
Debug.Assert(myClass.Origin.X == 10); //succeeds
}
}
class MyClass
{
private Point _origin;
public Point Origin
{
get => _origin;
set => _origin = value;
}
public void SetOrigin()
{
_origin.X = 10; //this works
//Origin.X = 10; // fails with CS1612;
}
}
The error you are getting is an indirect consequence of not understanding that a property returns a copy of a value type. If you are returned a copy of a value type and you do not assign it to a local variable then any changes you make to that copy can never be read and therefore the compiler raises this as an error since this cannot be intentional. If we do assign the copy to a local variable then we can change the value of X, but it will only be changed on the local copy, which fixes the compile time error, but will not have the desired effect of modifiying the Origin property. The following code illustrates this, since the compilation error is gone, but the debug assertion will fail:
您得到的错误是不理解属性返回值类型副本的间接后果。如果您返回一个值类型的副本并且您没有将它分配给局部变量,那么您对该副本所做的任何更改都无法读取,因此编译器将此作为错误引发,因为这不是故意的。如果我们确实将副本分配给本地变量,那么我们可以更改 X 的值,但只会在本地副本上更改,从而修复编译时错误,但不会达到修改 Origin 属性的预期效果。以下代码说明了这一点,因为编译错误消失了,但调试断言将失败:
class Program
{
static void Main(string[] args)
{
var myClass = new MyClass();
myClass.SetOrigin();
Debug.Assert(myClass.Origin.X == 10); //throws error
}
}
class MyClass
{
private Point _origin;
public Point Origin
{
get => _origin;
set => _origin = value;
}
public void SetOrigin()
{
var origin = Origin;
origin.X = 10; //this is only changing the value of the local copy
}
}