C# 堆栈 - Contains() 方法
C# 堆栈 Contains() 方法用于判断堆栈中是否存在元素。
该方法执行线性搜索,因此复杂度为 O(n),其中 n 为元素数量。
语法
以下是 C# 堆栈 Contains() 方法的语法 -
public virtual bool Contains (object? obj);
参数
此方法接受一个 obj 参数,表示堆栈中的元素。该值可以为 null。
返回值
如果在堆栈中找到该元素,则此方法返回 true。否则,返回 false。
示例 1:使用 Contains() 方法
以下是使用 Contains() 方法在堆栈中查找元素的基本示例 -
using System;
using System.Collections;
class Example {
public static void Main() {
Stack myStack = new Stack();
// 将元素插入到堆栈中
myStack.Push(1);
myStack.Push(2);
myStack.Push(3);
myStack.Push(4);
myStack.Push(5);
int element = 4;
bool res = myStack.Contains(element);
Console.WriteLine($"Is the {element} available?: {res}");
}
}
输出
以下是输出 -
Is the 4 available?: True
示例 2:检查字符串是否可用
让我们看另一个使用 Contains() 方法的示例,以检查字符串是否在堆栈中可用 -
using System;
using System.Collections;
class Example {
public static void Main() {
Stack myStack = new Stack();
myStack.Push("Hello");
myStack.Push("tutorialspoint");
myStack.Push("India");
myStack.Push("Good to know");
string element = "India";
bool res = myStack.Contains(element);
Console.WriteLine($"Is the {element} available?: {res}");
}
}
输出
以下是输出 -
Is the India available?: True
示例 3:在 Stack 中检查 Person 的详细信息
以下示例创建了一个 Person 对象。在这里,我们使用 Contains() 方法来验证 Person 的详细信息是否可用 -
using System;
using System.Collections.Generic;
class Person {
public string Name { get; set; }
public int Age { get; set; }
public Person(string name, int age) {
Name = name;
Age = age;
}
public override string ToString() {
return $"Name: {Name}, Age: {Age}";
}
// 重写 Equals 和 GetHashCode 来按值而不是引用比较对象
public override bool Equals(object obj) {
if (obj is Person other) {
return Name == other.Name && Age == other.Age;
}
return false;
}
public override int GetHashCode() {
return HashCode.Combine(Name, Age);
}
}
class Example {
static void Main() {
// 创建一个 Person 对象堆栈
Stack<Person> people = new Stack<Person>();
// 将 Person 对象推送到堆栈
people.Push(new Person("Aman", 25));
people.Push(new Person("Gupta", 24));
people.Push(new Person("Vivek", 26));
Console.WriteLine("People stack before Contains:");
foreach (var person in people) {
Console.WriteLine(person);
}
// 使用 contains 方法
bool res = people.Contains(new Person("Aman", 25));
Console.Write("Is this object avialable: " + res);
}
}
输出
以下是输出 -
People stack before Contains: Name: Vivek, Age: 26 Name: Gupta, Age: 24 Name: Aman, Age: 25 Is this object avialable: True

csharp_stack.html