【问题标题】:Class Instance Array Specific Method [duplicate]类实例数组特定方法[重复]
【发布时间】: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#


【解决方案1】:

如果你坚持像这样的语法

  arr.getThingFromID(55);

你可以实现一个扩展方法

  using System.Linq;

  ...

  static class ThingExtensions {

    public static Thing getThingFromID(this IEnumerable<Thing> source, int id) {
      if (null == source)
        return null;

      return source
        .FirstOrDefault(item => item?._id == id); 
    }  
  }

调用将好像arr 本身具有getThingFromID 方法:

  Thing result = arr.getThingFromID(55);

如果你想保留Thing getThingFromID(int id):

class Thing
{
    //TODO: I suggest put "private set" instead of "set"
    public int _id { get; set; }

    public Thing(int id)
    {
        _id = id;
    }

    public static Thing getThingFromID(int id, IEnumerable<Thing> source)
    {
        if (null == source)
            return null;

        return source
            .Where(item => item != null)
            .FirstOrDefault(item => item._id == id); 
    }
}

但你必须把它称为

Thing result = Thing.getThingFromID(55, arr); 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-12-13
    • 2017-09-12
    • 1970-01-01
    • 2011-10-25
    • 2020-11-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多