using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;namespace ListRead
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
} private List<StructTest> poList = null;
private void button1_Click(object sender, EventArgs e)
{
poList = new List<StructTest>();
for (int i = 0; i < 3; i++)
{
StructTest oTemp = new StructTest();
oTemp.Str1 = "AA";
oTemp.Str2 = "AA";
poList.Add(oTemp);
}
} private void button2_Click(object sender, EventArgs e)
{
for (int i = 0; i < poList.Count; i++)
{
poList[i].Str1 = "BB";
poList[i].Str2 = "BB";
}
} public struct StructTest
{
public string Str1;
public string Str2;
}
}
}
上面的代码直接编译通过不了 大家积极探讨下
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;namespace ListRead
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
} private List<StructTest> poList = null;
private void button1_Click(object sender, EventArgs e)
{
poList = new List<StructTest>();
for (int i = 0; i < 3; i++)
{
StructTest oTemp = new StructTest();
oTemp.Str1 = "AA";
oTemp.Str2 = "AA";
poList.Add(oTemp);
}
} private void button2_Click(object sender, EventArgs e)
{
for (int i = 0; i < poList.Count; i++)
{
poList[i].Str1 = "BB";
poList[i].Str2 = "BB";
}
} public struct StructTest
{
public string Str1;
public string Str2;
}
}
}
上面的代码直接编译通过不了 大家积极探讨下
StructTest st = poList[i];
st.Str1 = "BB";
st.Str2 = "BB";
{
public Symbol MySymbol { get; set; }
public Symbol GetSymbol()
{
return new Symbol(10);
} Test()
{
this.symbol.Code = 10; //这也是会报错的。
GetSymbol().Code = 10;//这还是会报错。
}
}这是因为C#的return处理,如果传的是引用类型,传递的是一个引用,如果是值类型,则传递的是拷贝。所以对return回来的值类型做修改只是修改的一个副本,这很容易引起歧义,使你的代码达不到想要的效果。C#为了避免这个问题和C#的严谨,所以在编译时作为错误处理。
“属性”的get访问器也是要调用return的,所以属性也有这个限制。
索引和数组不同的地方在于,索引器并没有直接对应引用数据存储的地方,而数组则有。
索引器有get访问器与set访问器,用来指明要读取或写入索引器元素时,需要执行的代码。
list的[]操作实际上是索引器,所以s1[0]是执行return的,所以也有这个问题。
数组是直接取数据,所以没有这个问题。
list将Item属性实现为[]操作,所以a[i]是执行return的,t.Student通过属性访问显然也是执行return的,STRUCT是值类型的,当用下标操作返回时,是值拷贝操作。就是将a[i]中的struct赋给临时变量,而这个赋值过程是值拷贝,值拷贝是内存复制,所以当赋值"jhon"时,只更改临时变量,而不会改变LIST中的元素所指向的内存。如果确实需要这样能直接赋值,需要使用class,这样就都是引用了,不存在因为值拷贝而引发“不是变量”的问题。
{
public int Code;
public Symbol(int code)
{
Code = code;
}
} List<Symbol> s1 = new List<Symbol>();
Symbol[] s2 = new Symbol[1];
s1.Add(new Symbol(1));
s2[0] = new Symbol(2); s1[0].Color = 10; ----报错
s2[0].Color = 20; ----不报错这个应该在前面