C#项未添加到List< String> [英] C# Item not being added to List<String>

查看:53
本文介绍了C#项未添加到List< String>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是我在Azure中实现ICollector界面的情况.

Below is my implementation of ICollector interface from Azure.

class TestCollector<T> : ICollector<T>
{
    public List<T> Collector => new List<T>();

    public void Add(T item)
    {
        Collector.Add(item);
    }
}

将项目添加到TestCollector时,收集器的数量仍然保持为0.

When the item is added on the TestCollector, the Collector's count still remain as 0.

不添加它的原因是什么?我应该为TestCollector创建一个单独的构造函数并在其中初始化Collector吗?

What is the reason it's not being added? Should I create a separate constructor for TestCollector and initialize Collector inside?

推荐答案

以下错误

public List<T> Collector => new List<T>();    

箭头功能是方法的简写语法.您编写的内容等同于以下内容:

The arrow function is short-hand syntax for a method. What you've written is equivalent to the following:

public List<T> Collector()
{
    return new List<T>();
}

因此,每次调用Collector时,您都会返回一个新列表,向其中添加一个项目,然后不再引用该列表.

So every time you call Collector, you return a new list, add an item to it, and then no longer have a reference to that list.

如果您需要一个字段,请将其替换为:

If you need a field, replace it with this:

public List<T> Collector = new List<T>();    

我错过了这样一个事实,您需要使用Collector方法来实现您的接口.在这种情况下,可能有必要在字段中初始化列表,然后在实现Collector的过程中按如下所示将其返回:

I've missed the fact that you need the Collector method in order to implement your interface. In that case it might make sense to initialise the list in a field, and then return it in your implementation of Collector as follows:

class TestCollector<T> : ICollector<T>
{
    private List<T> Collector _collector = new List<T>();
    public List<T> Collector => _collector;

    public void Add(T item)
    {
        _collector.Add(item);
    }
}

这篇关于C#项未添加到List&lt; String&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆