首页 技术 正文
技术 2022年11月8日
0 收藏 541 点赞 1,331 浏览 1107 个字
using UnityEngine;
using System.Collections;
using System.Xml.Linq;
using UnityEditor;
using System;public class NewBehaviourScript : MonoBehaviour { struct MVec3{
public float x;
public float y;
public float z;
} class CTest{ public MVec3 posx;
public MVec3 pos { set; get; }//等同于下面的写法-> /*MVec3 dv = new MVec3 ();
public MVec3 pos{
set{ dv = value; }
get{ return dv;}
}*/ } CTest otest; // Use this for initialization
void Start () {
otest = new CTest (); otest.pos.x = ;
otest.posx.x = ;
gameObject.transform.position.x = ; Debug.Log ("ot.pos.x={0}" + otest.posx.x); }
// Update is called once per frame
void Update () {
Vector3 vec3 = gameObject.transform.position;
}
}

编译时出现如下错误:

C# 【无法修改XX返回值,因为它不是变量】

可以看到34行和36行都出现了编译错误,而35行则正确编译。原因分析:

C#中,reference类型变量存储在堆上,value类型存储在栈上。pos, posx, position都是值类型,为什么会有不同的编译结果呢。区别在于 pos, position是属性,posx是字段。具体分析如下:

32行:new了一个引用类型CTest的对像otest,这时在堆上为对象分配了一片内存,内存大小为pos的三个float和posx的三个float。

34行:由于pos是一个属性,otest.pos将调用属性的get方法,方法的调用是使用栈来进行的,get方法在栈上分配一个临时变量temp来返回pos的的值。即otest.pos返回了一个分配在栈上的临时变量的地址,而otest.pos.x = 10则是试图对栈上临时变量的X进行赋值。这个操作并非不合法,然而是没有意义的,于是编译器就阻止了我们的这个无意义操作,以避免隐患。同理36行。

明白了这个,就容易理解35行为什么是正确的了。otest.posx是一个正常的取地址操作,表示取出otest所在堆内存中的posx变量的地址,这个地址是对象的堆内存中的。

otest.posx.x = 10则是修改堆内存中posx的x的值。

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,492
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,907
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,740
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,494
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:8,132
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:5,295