且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

[C#]从方法返回一个数组?

更新时间:2023-02-14 17:00:31

区别的原因是你的 GetNames 方法每次调用时都会创建一个新数组。您可以像这样重写它

The reason for the difference is that your GetNames method is creating a new array each time it is called. You could rewrite it like this

static string[] GetNames()
        {
            return new [] { "Matthew", "Mark", "Luke", "John" };
            
        }

所以 strArr strArr2在您的示例中,引用了不同的数组。提出关于字符串不变性的观点是有效的,但这并不是你所说明的行为的原因。

So strArr and strArr2, in your example, are referencing different arrays. The point raised about immutability of strings is valid but it is not the reason for the behaviour you have illustrated.


这很复杂。数组是引用,但它是对引用数组的引用。字符串是一种特殊情况,因为它们是不可变的:一旦创建,它们就无法更改,因此下面的代码不一定按照你的想法行事:

It's complicated. An array is a reference, but it's a reference to an array of references. And strings are a special case, because they are immutable: once created, they cannot be changed, so the following code doesn't necessarily do what you might think:
string x = "XXX";
string y = x;
x = "YYY";
Console.WriteLine("{0}:{1}", x, y);

这将打印YYY:XXX,因为不变性意味着字符串引用就像一个值 - 而不是更改现有引用内容,创建一个新引用,因此旧字符串不受影响完全没有。

当你运行你的代码时,你会得到类似的效果:

This will print "YYY:XXX" because the immutability means that the string reference acts like a value - instead of changing the existing reference content, a new reference is created, so the old string is not affected at all.
When you run your code, you get a similar effect:

string[] strArr = GetNames();

返回对字符串数组的引用。

returns a reference to an array of strings.

string[] strArr2 = GetNames();

还返回对数组的引用字符串。

但是...它们不是相同的参考,因为它不是同一个数组!

试试吧:

Also returns a reference to an array of strings.
But ... they aren't the same reference, because it isn't the same array!
Try it:

if (strArr == strArr2) Console.WriteLine("Same");
else Console.WriteLine("Different");

将始终打印不同,因为尽管字符串相同,但数组不是。



每次执行这段代码:

Will always print "Different" because despite the strings being the same, the arrays are not.

Every time you execute this code:

string[] ret = { "Matthew", "Mark", "Luke", "John" };

框架创建一个新的数组,并用字符串填充它以便你返回。

如果你想分享它们,你需要返回相同的数组:

The framework creates a new array, and fills it with the strings for you to return.
If you want to share them, you would need to return the same array:

static string[] ret = { "Matthew", "Mark", "Luke", "John" };
static string[] GetNames()
    {
    return ret;
    }

现在,您将获得

Now, you will get

strArr[0] = Nik and strArr2[0] = Nik

如果进行比较,则为相同。

And "Same" if you do the comparison.