且构网

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

如何在C#中返回一个字符串数组

更新时间:2022-11-11 13:31:26

Quote:

无法将类型对象隐式转换为字符串

cannot implicitly convert type object to string

那是因为 MemberList [i] 是一个对象而不是 string

That's because MemberList[i] is an object not a string.


protected List<string> FindTargetMember(ArrayList MemberList,String TargetMember)
    {
        List<string> list = new List<string>();
        for (int i = 0; i < MemberList.Count; i++)
        {
            if (TargetMember.Equals(MemberList[i]))
            {
               list.Add(MemberList[i].Name.ToString());
// Assuming Name property is there in MemberList objeect. If it's not you can modify the code by yourself.
            }
        }
        return list;
}



-KR


-KR


由于 ArrayList 是一个对象集合,您必须将项目转换为字符串(您可以只返回输入字符串)。

但请注意:返回找到的项目的索引更有意义(或 -1 是它没有找到。)
Since ArrayList is a collection of objects, you have to cast the item to a string (you could just return the input string).
However, please note: it makes more sense to return the index of the found item (or -1 is it is not found).