此方法用于创建堆栈的浅表副本。它只是创建堆栈的副本。该副本将引用内部数据阵列的克隆,但不引用原始内部数据阵列。
Syntax: public virtual object Clone ();
Return Value: The method returns an Object which is just the shallow copy of the Stack.
示例1:让我们看一个示例,该示例不使用Clone()方法,而是使用赋值运算符’=’直接复制Stack。在下面的代码中,即使我们从myStack2中的Pop()元素也可以看到, myStack的内容也已更改。这是因为’=’只是将myStack的引用分配给myStack2,而不创建任何新的Stack。但是Clone()创建了一个新的Stack。
// C# program to Copy a Stack using
// the assignment operator
using System;
using System.Collections;
class GFG {
// Main Method
public static void Main(string[] args)
{
Stack myStack = new Stack();
myStack.Push("C");
myStack.Push("C++");
myStack.Push("Java");
myStack.Push("C#");
// Creating a copy using the
// assignment operator.
Stack myStack2 = myStack;
// Removing top most element
myStack2.Pop();
PrintValues(myStack);
}
public static void PrintValues(IEnumerable myCollection)
{
// This method prints all
// the elements in the Stack.
foreach(Object obj in myCollection)
Console.WriteLine(obj);
}
}
输出:
Java
C++
C
范例2:
// C# program to illustrate the use
// of Stack.Clone() Method
using System;
using System.Collections;
class MainClass {
// Main Method
public static void Main(string[] args)
{
Stack myStack = new Stack();
myStack.Push("1st Element");
myStack.Push("2nd Element");
myStack.Push("3rd Element");
myStack.Push("4th Element");
// Creating copy using Clone() method
Stack myStack3 = (Stack)myStack.Clone();
// Removing top most element
myStack3.Pop();
PrintValues(myStack);
}
public static void PrintValues(IEnumerable myCollection)
{
// This method prints all the
// elements in the Stack.
foreach(Object obj in myCollection)
Console.WriteLine(obj);
}
}
输出:
4th Element
3rd Element
2nd Element
1st Element
参考:
- https://docs.microsoft.com/zh-cn/dotnet/api/system.collections.stack.clone?view=netframework-4.7.2#System_Collections_Stack_Clone