【问题标题】:Input data for indexer索引器的输入数据
【发布时间】:2022-12-19 01:07:44
【问题描述】:

我有一个带有方法删除的类,它需要从 CustomerList 中删除 Customer。

    public class ObservableList<T>
    {
        List <T> CustomerList = new List<T>();
        public void Remove(ObservableList<Customer> list) // not correct 
        {
            //something for delete from list;
        }
    }

此类中的索引器:

    public T this[int indexer]
    {
        get { return CustomerList[indexer]; }
        set { CustomerList.Add(value); }
    }

用于测试此方法的字符串如下所示:

ObservableList<Customer> list = new ObservableList<Customer>();

list.Remove(list[2]);

问题是,如何正确格式化此方法的输入数据(删除)?索引器是否在我的代码中正确执行?

【问题讨论】:

  • 你能解释一下为什么你有具体类型列表的通用包装器吗? ObservableList&lt;T&gt;中的T有什么意义?这应该如何工作,例如用户将创建ObservableList&lt;decimal&gt;
  • 这段代码有很多问题,我首先建议您查看现有集合是否比尝试编写自己的集合不能更好地满足您的需求。值得注意的是,ObservableCollection 已经成为现实。
  • 您还可以解释一下“不正确”的评论吗?什么是不正确的?为什么不正确?

标签: c#


【解决方案1】:

要正确格式化 Remove 方法的输入数据,您需要将 Customer 对象作为参数传递,而不是 ObservableList 对象。您可以使用索引器从 CustomerList 的特定索引处获取 Customer 对象,并将其传递给 Remove 方法。

下面是一个示例,说明如何修改 Remove 方法以接受 Customer 对象作为参数,并从 CustomerList 中删除该对象:

    public void Remove(Customer customer)
{
    CustomerList.Remove(customer);
}

要使用 Remove 方法,您可以使用索引器从 CustomerList 中获取指定索引处的 Customer 对象,并将其传递给 Remove 方法:

    ObservableList<Customer> list = new ObservableList<Customer>();

// Use the indexer to get the Customer at index 2 from the CustomerList
Customer customer = list[2];

// Remove the customer from the CustomerList
list.Remove(customer);

在您的代码中,索引器已正确执行。它允许您在 CustomerList 中的特定索引处获取和设置 Customer 对象。

【讨论】:

  • 索引器仅在其 getter 中是正确的,而不是在其 setter 中。
  • 索引器设置器不正确。它添加了一个值,根本不使用索引。
  • @JeroenMostert 我敢打赌你正在与之交谈的是 ChatGPT =)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-07-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多