可以使用 ArrayList 的 Find 方法来查找某个 struct,如果找到了则返回该 struct,如果没有找到则返回 null。以下是一个示例代码:

using System;
using System.Collections;

public struct MyStruct {
    public int id;
    public string name;
}

class Program {
    static void Main(string[] args) {
        ArrayList list = new ArrayList();
        list.Add(new MyStruct { id = 1, name = 'John' });
        list.Add(new MyStruct { id = 2, name = 'Mary' });
        list.Add(new MyStruct { id = 3, name = 'Tom' });

        MyStruct result = FindStruct(list, 2);
        if (result.id != 0) {
            Console.WriteLine('Found struct: id={0}, name={1}', result.id, result.name);
        } else {
            Console.WriteLine('Struct not found');
        }
    }

    static MyStruct FindStruct(ArrayList list, int id) {
        MyStruct result = new MyStruct();
        foreach (MyStruct s in list) {
            if (s.id == id) {
                result = s;
                break;
            }
        }
        return result;
    }
}

在上面的代码中,我们定义了一个 MyStruct 结构体,并使用 ArrayList 存储多个 MyStruct。然后我们编写了一个 FindStruct 函数,该函数接受一个 ArrayList 和一个 id 参数,用于查找 id 对应的 MyStruct。如果找到了,则返回该 MyStruct,否则返回一个默认值。最后我们调用 FindStruct 函数查找 id 为 2 的 MyStruct,并根据返回值判断是否找到。

C# ArrayList 查找 Struct:示例代码及方法

原文地址: https://www.cveoy.top/t/topic/nEq1 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录