如何使用 Reverse 方法反转数组。 C#

How to reverse an array using the Reverse method. C#

出于某种原因,当我应用反向方法时,没有任何变化。

public static string ReverseString(string word)
    {
        char[] myArray = word.ToCharArray();
        myArray.Reverse();

        string ans = string.Join("", myArray);

        return ans;
    }

方法Reverse是returns基于原始项的新数组(或集合)的方法。

public static string ReverseString(string word)
{
    char[] myArray = word.ToCharArray();
    myArray = myArray.Reverse().ToArray(); //<-- Call ToArray() method to convert back to the array and execute the deffered action.

    string ans = string.Join("", myArray);

    return ans;
}

This method is implemented by using deferred execution. The immediate return value is an object that stores all the information that is required to perform the action. The query represented by this method is not executed until the object is enumerated either by calling its GetEnumerator method directly or by using foreach in Visual C# or For Each in Visual Basic.

Unlike OrderBy, this sorting method does not consider the actual values themselves in determining the order. Rather, it just returns the elements in the reverse order from which they are produced by the underlying source.

您需要将 return 值存储在变量中:

var reversed = myArray.Reverse();

这是您正在使用的 Reverse() 方法的签名,顺便说一下,这是 Enumerable class:

中的扩展方法
public static IEnumerable<TSource> Reverse<TSource>(this IEnumerable<TSource> source);

看到 return 类型是一个 IEnumerable,因此您需要存储它然后使用它。

你可以这样做:

public static string ReverseString(string word)
{
    return string.IsNullOrWhiteSpace(word) ? string.Empty 
        :  string.Concat(word.Reverse());
}

问题是 myArray.Reverse() 不修改 myArray。此方法 returns char 的 IEnumerable 与 myArray 的相反。

试试这个:

var reversed = myArray.Reverse();

然后使用反向操作。

也许您将正在使用的方法与 static Array.Reverse 混淆了,后者确实是 void 方法?

Array.Reverse Method (Array)


您使用的是 IEnumerable 的 LINQ 扩展方法,您可以在此处找到其参考资料:

Enumerable.Reverse Method (IEnumerable)


不过对于你的具体情况,我会使用这个单行线:

return new string(word.Reverse().ToArray()); 

尝试 Array.Reverse(myArray) 而不是 myArray.Reverse()

您正在混淆 Enumerable.Reverse and Array.Reverse 方法。

IEnumerable<char>.Reverse: Returns 一个新的反转数组而不改变旧数组

myArray = myArray.Reverse();

Array.Reverse: 将反转输入数组的 Void 方法

Array.Reverse(myArray);

你应该Array.Reverse(myArray)