C# 将值指定给数组的索引和将值指定给数组的索引别名之间有什么区别?
我认为你的问题标题显示了潜在的误解: 数组索引的别名 当您指定这样的字符串时:C# 将值指定给数组的索引和将值指定给数组的索引别名之间有什么区别?,c#,arrays,C#,Arrays,我认为你的问题标题显示了潜在的误解: 数组索引的别名 当您指定这样的字符串时: public string[] arrTestResults = new string[8]; public string TestName; [TestInitialize] public void SetupTest() { // Assigning aliases to array indexes TestName = arrTestResults[0] = "";
public string[] arrTestResults = new string[8];
public string TestName;
[TestInitialize]
public void SetupTest()
{
// Assigning aliases to array indexes
TestName = arrTestResults[0] = "";
}
public void General()
{
arrTestResults[0] = "Test 1: General"; // works
TestName = "Test 1: General"; // does not work. Quick Watch says TestName = Null. WHY?
您没有为arrTestResults[0]
中包含的内容分配别名,而是将对arrTestResults[0]
所指向字符串的引用复制到TestName
中。这是对字符串引用的副本,但不是别名
稍后,当您为TestName
赋值时:
TestName = arrTestResults[0];
这将复制一个新引用,覆盖旧引用。它对数组中的引用没有任何作用,因为它是一个单独的副本。这不是别名;这是一个自变量
无法使变量成为另一个变量或数组元素的别名(除非使用不安全的代码)。
TestName
不是arrTestResults[0]
的别名
我假设arrTestResults
是string[]
,而TestName
也是
arrTestResults[0]
是一个存储位置,其值引用string
的实例
TestName = "Test 1: General";
TestName
是一个存储位置,其值引用string
的实例
TestName = "Test 1: General";
不会使TestName
成为arrTestResults[0]
的别名。相反,它为存储位置TestName
和存储位置arrTestResults[0]
分配一个对字符串的实例的引用,该实例等于“
。也就是说,有一个对“
的引用。该引用被分配给arrTestResults[0]
和TestName
。这与
TestName = arrTestResults[0] = "";
这里,x
不是y
的别名。我们刚刚将值17
复制到y
和x
。在我们的例子中,值就是引用。对“
的引用复制到arrTestResults[0]
和TestName
然后
将新引用分配给存储位置arrTestResults[0]
很像
arrTestResults[0] = "Test 1: General";
TestName = "Test 1: General";
然后
y = 42;
为存储位置TestName
分配一个新引用。它不会改变arrTestResults[0]
的值,因为这两个存储位置不同。同样,这很像
arrTestResults[0] = "Test 1: General";
TestName = "Test 1: General";
当您说“不工作”时,这不会改变y
的值,您的意思是什么?您会遇到什么样的错误?我快速观察了一下,发现TestName=null TestName是什么类型的对象?向我们展示它的declarationTestName获取“”,而不是arrTestResults位置0处的内容。