【发布时间】:2021-06-27 17:15:32
【问题描述】:
我正在尝试使用 getThingFromID 返回具有指定 ID 的 Thing[] 数组中的对象。 如何在 C# 中执行此操作?
class Thing
{
public int _id { get; set; }
public Thing(int id)
{
_id = id;
}
Thing getThingFromID(int id)
{
}
}
class Program
{
static void Main(string[] args)
{
Thing[] arr = new Thing[3];
arr[0] = new Thing(44);
arr[1] = new Thing(55);
arr[2] = new Thing(66);
arr.getThingFromID(55);
{
{
【问题讨论】:
-
首先,
arr.getThingFromID不会编译。您需要让getThingFromID采用Thing[]参数或将其转换为扩展方法。至于方法体中的内容,您可以从arr.FirstOrDefault(t => t._id == id);之类的内容开始。作为旁注,您应该坚持使用 C# naming convention。 -
将
getThingFromID()方法放在Thing类中对我来说似乎没有用。Thing类对arr数组一无所知。也就是说,就实际问题而言,arr.FindIndex(x => x._id == id)将为您提供arr元素的索引,其中属性_id等于id。查看副本。 -
您好,您需要使用“扩展”方法来实现此目的。您可以查看此答案以供参考:stackoverflow.com/questions/1183083/…
-
你为什么不用字典?看这段代码:dotnetfiddle.net/XQDPqe
-
@CarlosGarcia 这是个好主意
标签: c#