集合作为out参数
本文关键字:参数 out 集合 | 更新日期: 2023-09-27 18:30:07
我对集合的概念很陌生。我有一个类对象(Officer
),它有几个属性,其中三个属性构成了军官的名称。
我还有一个名为Company
的独立类对象,它位于Officer
对象之上。company
包含军官的选择,因此为了显示军官的姓名,我需要在两者之间提供某种形式的参考:
private List<Officer> officerList;
public void addOfficer(Officer off)
{
officerList.Add(off);
}
现在,要真正将数据返回到另一个类,我需要创建一个列表(毫无意义),创建大量Officer
对象(效率低下),或者返回一个集合。
public void getOfficerNames(out *something* names) //I want to use a collection
//here... I think
{
foreach (Officer o in officerList)
{
names = o.Title
+ o.ForeName
+ o.SurName;
}
}
这是我所了解的,因为我很难理解
a) 如何实现集合和
b) 如果这是正确的做法。
您不需要out
来修改传递给函数的引用类型,所以这就足够了:
public void GetOfficerNames(List<string> names)
{
foreach (Officer o in officerList)
{
names.Add(o.Title + o.ForeName + o.SurName);
}
}
此外,只返回名称会更可读:
public IEnumerable<string> GetOfficerNames()
{
return officerList.Select(o => o.Title + o.ForeName + o.SurName);
}
然后你可以这样使用它:
var names = new List<string>();
//...
names.AddRange(GetOfficerNames());
或者只是:
var names = GetOfficerNames().ToList();
out
主要用于值类型,使其通过引用传递。但是,如果需要初始化引用类型,它也可以与引用类型一起使用。因此,在您的情况下,示例如下:
public void GetOfficerNames(out List<string> names)
{
names = new List<string>();
foreach (Officer o in officerList)
{
names.Add(o.Title + o.ForeName + o.SurName);
}
}
然后它会被这样使用:
List<string> officerNames; // uninitialized
GetOfficerNames(out officerNames);
foreach (var name in officerNames) // out guarantees officerNames
{ // will be initialized here
//...
}
然而,这是很少需要的,不太可读,因此不鼓励和很少使用。
您是否考虑过以字符串形式返回名称列表?
public List<string> getOfficerNames()
{
List<string> names = new List<string>;
foreach (Officer o in officerList)
{
names.Add(o.Title + o.ForeName + o.SurName);
}
return names;
}
如果您希望字符串中的每个军官名称都可以作为枚举或列表访问,我认为最好将其作为枚举
public IEnumerable<string> getOfficerNames() //I want to use a collection
//here... I think
{
foreach (Officer o in officerList)
{
yield return o.Title + " " + o.ForeName + " "+ o.SurName;
}
}