认真CS丨交错数组、数组协变(待补充)、Clone方法
using System;
class MyClass
{
class A
{
public int A1 = 10;
}
class B:A
{
public int B1 = 20;
}
static void Main()
{
int a=0;
Console.WriteLine("a={0}",a);
int[][] Arr = new int[2][];
Arr[0] = new int[] { 2, 3 };
Arr[1] = new int[] { 5,6 };
foreach (int[] test in Arr)
{
Console.WriteLine("Game Begin");
foreach (int test1 in test)
{
a+=test1;
Console.WriteLine("test1={0},a={1}", test1,a);
}
Console.WriteLine("a={0}",a);
}
A[] AAry1 = new A[3];
A[] AAry2 = new A[2];
AAry2[0] = new B();
Console.WriteLine("AAry2[0].B1={0}", AAry2[2].B1);
AAry2[1] =new B();
AAry2[1].B1 = 25;
Console.WriteLine("AAry2[0].B1={0}", AAry2[1].B1);
}
}
*/
using System;
class A
{
public int b=10;
}
class B:A
{
public int b=20;
}
class MyClass
{
static void Main()
{
A[] AArray1 = new A[3];
AArray1[0] = new B(); //派生类也可赋值给基类类型成员
Console.WriteLine(AArray1[0].b); //但实际上,AArray[0]里面还是他自己类型(A类型)的成员。
}
}
//书籍中描述:数组协变是将B类型的对象赋值给AArray1类型的数组,但在此地不知具体含义,此地有疑问。
//在以下情况可使用数组协变:
//1.数组是引用数组。
//2.在复制对象类型和数组类型之间有隐式转换或显示转换。
using System; //Clone方法
class MyClass
{
class a
{
public int a1 = 1;
}
static void Main()
{
tip1: int[] Arr = new int[4];
for (int i = 1; i < 5; i++)
Arr[i-1] = i;
int[] test1 = (int[])Arr.Clone();
foreach (int test2 in Arr)
{
Console.WriteLine("test={0}",test2);
}
tip2: a[] ax = new a[4];
for(int i = 0; i < 4; i++)
{
ax[i] = new a();
Console.WriteLine("ax{0}={1}",i,ax[i].a1); //Clone值类型对象,会在栈克隆对象的另一份数据,两者无相互影响。
}
a[] testax = (a[])ax.Clone(); //不止可以返回int型
for (int i = 0; i < 4; i++)
{
testax[i].a1 = testax[i].a1+10;
Console.WriteLine("ax{0}={1}", i, testax[i].a1); //Clone引用类型克隆的是对象的引用,修改其值,原对象值跟着改动。
}
}
}
- 上一篇:没有了
- 下一篇:没有了