【发布时间】:2022-11-16 02:32:46
【问题描述】:
file class C
{
public int IntField1;
}
file struct S
{
public int IntField1;
}
file class StructureVsClassWhenCopying
{
private static void v1()
{
System.Console.WriteLine("v1");
}
private static void v2()
{
System.Console.WriteLine("v2");
}
public static void Main()
{
C c1 = new();
c1.IntField1 = 1;
C c2 = c1;
c1.IntField1 = 2;
System.Console.WriteLine(c2.IntField1); // 2, because class is a reference-type
S s1 = new();
s1.IntField1 = 1;
S s2 = s1;
s1.IntField1 = 2;
System.Console.WriteLine(s2.IntField1); // 1, because struct is a value type
string str1 = "old string";
string str2 = str1;
str1 = "new string";
System.Console.WriteLine(str2); // old string, because string is immutable
System.Action a1 = v1;
System.Action a2 = a1;
a1 -= v1;
a1 += v2;
a2.Invoke(); //v1. Why?
}
}
我想知道引用和值类型的复制。我已经通过类(引用类型)、结构(值类型)和字符串(也是引用类型,但不可变)理解了这个示例。但是委托也是引用类型,为什么它们表现得像结构和字符串?
【问题讨论】:
标签: c# delegates value-type copying reference-type