不能修改返回值误差C# [英] Cannot modify the return value error c#

查看:145
本文介绍了不能修改返回值误差C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是自动实现的属性。
我想解决以下是声明自己的后盾变量的最快方法?

 公共原点{搞定;组; }Origin.X = 10; //失败,CS1612


  

错误信息:不能修改恩pression'的返回值,因为
  它不是一个变量


这是试图修改是中间前pression结果的值类型。由于该值不坚持,该值将保持不变。

要解决此错误,前pression的结果存储在一个中间值,或使用引用类型的中间前pression。


解决方案

这是因为是值类型(结构)。

由于这个原因,当您访问原产地属性你访问的复制的由类持有的价值,而不是价值本身,你会与一个引用类型(),因此,如果您设置了 X 就可以了财产,那么你'重新设定在副本上的属性,然后将其丢弃,离开原来的值不变。这可能不是你打算什么,这就是为什么编译器警告你一下吧。

如果你想改变就在 X 价值,你需要做的是这样的:

 产地=新的点(10,Origin.Y);

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.

解决方案

This is because Point is a value type (struct).

Because of this, when you access the Origin property you're accessing a copy of 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.

If you want to change just the X value, you need to do something like this:

Origin = new Point(10, Origin.Y);

这篇关于不能修改返回值误差C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆