var x = new People { { “rr”, “ss” } } 创建了一个新的class实例,但为什么没有加上(),测试了一下 原来他实现了IEnumerable:如下
class People : System.Collections.IEnumerable
{
public IEnumerator GetEnumerator()
{
throw new NotImplementedException();
}
public void Add(string key, object value) {
}
}
static void Main(string[] args)
{
var x = new People { { "rr", "ss" } };
}
这样就不会报错了,但是 这个并不是完整的结构,我们举个完整结构的例子
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public Person(string firstName, string lastName)
{
this.FirstName = firstName;
this.LastName = lastName;
}
}
另外通过People类来实现IEnumerable和IEnumerator接口.
//实现IEnumerable接口
public class People :IEnumerable
{
public Person [] pers;
public People(Person [] ps)
{
this.pers = ps;
}
public IEnumerator GetEnumerator()
{
//foreach(Person p in pers)
// {
// yield return p;
// }
return new People1(pers);
}
}
//实现IEnumerator接口
public class People1 : IEnumerator
{
public Person[] pers;
public People1(Person[] per)
{
this.pers = per;
}
int position = -1;
public bool MoveNext()
{
position++;
return position < pers.Length;
}
public void Reset()
{
position=-1;
}
public object Current
{
get
{
try
{
return pers[position];
}
catch(IndexOutOfRangeException ex)
{
throw new InvalidOperationException();
}
}
}
}
附录
public interface IEnumerable
{
//IEnumerable只有一个方法,返回可循环访问集合的枚举数。
IEnumerator GetEnumerator() ;
}
public interface IEnumerator
{
// 方法
//移到集合的下一个元素。如果成功则返回为 true;如果超过集合结尾,则返回false。
bool MoveNext();
// 将集合设置为初始位置,该位置位于集合中第一个元素之前
void Reset();
// 属性:获取集合中的当前元素
object Current { get; }
}