C#: 关于struct 和 class 的试验
class Try_StructClass
{
public void Test()
{
Number a = 1;
Number b = a;
a = 2;
WriteLine($"a={a}, b={b}"); //a=2, b=1
Text A = 1;
Text B = A;
A = 2;
WriteLine($"A={A}, B={B}"); //A=2, B=1
var arrA = new Number[] { 1, 2, 3 };
var arrB = arrA;
arrA[1] = 10;
WriteLine($"arrA={string.Join(",", arrA)}, arrB={string.Join(",", arrB)}"); //arrA=1,10,3, arrB=1,10,3
var arrC = new Text[] { 1, 2, 3 };
var arrD = arrC;
arrC[1] = 10;
WriteLine($"arrC[1]={arrC[1]}, arrD[1]={arrD[1]}"); //arrC[1]=10, arrD[1]=10
var arrE = new double[] { 1, 2, 3 };
var arrF = arrE;
arrE[1] = 10;
WriteLine($"arrE[1]={arrE[1]}, arrF[1]={arrF[1]}"); //arrE[1]=10, arrF[1]=10
ReadKey();
}
struct Number
{
double Value;
private Number(double Val)
{
this.Value = Val;
}
public static implicit operator double(Number number)
{
return number.Value;
}
public static implicit operator Number(double Value)
{
return new Number(Value);
}
public override string ToString()
{
return this.Value.ToString();
}
}
class Text
{
double Value;
private Text(double val)
{
this.Value = val;
}
public static implicit operator double(Text text)
{
return text.Value;
}
public static implicit operator Text(double val)
{
return new Text(val);
}
public override string ToString()
{
return this.Value.ToString();
}
}
}