C#-如何在不使用索引器的情况下获取自定义集合的第一项?

C#-如何在不使用索引器的情况下获取自定义集合的第一项?,c#,arrays,class,collections,C#,Arrays,Class,Collections,因此,我试图构建一个自定义类型的集合,如果我不使用索引器,它可以访问集合中的第一项。 假设课程开始时是这样的 public class myCollection : IEnumerable<myCustomObject> { ... 有没有办法做到这一点 编辑:似乎有一种方法可以将关键字“this”用作构造函数的一部分,但我不知道如何实际这样做,也不知道它是否能满足我的需要。我不理解类结构从集合中递减并拥有集合的逻辑,但我想我不需要: var coll = new myCollec

因此,我试图构建一个自定义类型的集合,如果我不使用索引器,它可以访问集合中的第一项。 假设课程开始时是这样的

public class myCollection : IEnumerable<myCustomObject>
{
...
有没有办法做到这一点


编辑:似乎有一种方法可以将关键字“this”用作构造函数的一部分,但我不知道如何实际这样做,也不知道它是否能满足我的需要。

我不理解类结构从集合中递减并拥有集合的逻辑,但我想我不需要:

var coll = new myCollection();    //for this to work your myCollection class needs an accessible constructor
coll.someMember = "test";         //for this to work your myCollection class needs a property called someMember
coll[3].someMember = "test3";     //for this to work your myCollection class needs an indexer that uses the parent collection's ElementAt and myCustomObject class needs a property called someMember
“您的myCollection类需要索引器”是指您需要类似以下属性的内容:

public myCustomObject this[int idx]{
  get { return base.ElementAt(idx); }
}

这是一个奇怪的请求,你应该考虑你的代码是否对未来的开发人员有点迷惑,但是你可以通过让你的集合实现与你的集合类型相同的接口来完成它:

    public interface IMyCustomObject
    {
        string SomeMember { get; }
    }

    public class MyCustomObject : IMyCustomObject
    {
        public string SomeMember => "Hi";
    }

    public class MyCollection : IEnumerable<MyCustomObject>, IMyCustomObject
    {            
        public string SomeMember => this.FirstOrDefault()?.SomeMember;
    }
公共接口IMyCustomObject
{
字符串SomeMember{get;}
}
公共类MyCustomObject:IMyCustomObject
{
公共字符串SomeMember=>Hi;
}
公共类MyCollection:IEnumerable,IMyCustomObject
{            
公共字符串SomeMember=>this.FirstOrDefault()?.SomeMember;
}

为什么您的类
有-a
集合,也有
is-a
集合?
IEnumerable
允许您枚举而不是编辑或执行随机访问,
ICollection
构建在
IEnumerable
之上,并添加添加、删除和计数项的功能
IList
扩展
ICollection
以添加索引器。也许您只是想实现
IList
?或者,您可以继续使用
IEnumerable
,但添加一个索引器:I。。。我想这就是我最初学习如何制作定制集合的方式。现在我想起来,没有任何意义。谢谢,我将删除它。@Martin Costello,谢谢,我将查看IList和索引器。谢谢!我不确定索引器的属性。
    public interface IMyCustomObject
    {
        string SomeMember { get; }
    }

    public class MyCustomObject : IMyCustomObject
    {
        public string SomeMember => "Hi";
    }

    public class MyCollection : IEnumerable<MyCustomObject>, IMyCustomObject
    {            
        public string SomeMember => this.FirstOrDefault()?.SomeMember;
    }