IEnumerable C# Class How-to

本文关键字:How-to Class IEnumerable | 更新日期: 2023-09-27 18:28:16

下面是我的类。我需要使它可枚举。我在网上查了一下,虽然我找到了很多文件,但我还是丢失了。我想这绝对是我第一次问这个问题,但有人能不能让这个该死的东西对我来说是可枚举的,我会从那里弄清楚的。我使用的是C#ASP.Net 4.0

    public class ProfilePics
{
    public string status { get; set; }
    public string filename { get; set; }
    public bool mainpic { get; set; }
    public string fullurl { get; set; }
}

IEnumerable C# Class How-to

嗯。。。如果你只想让某人"让这个该死的东西变得可枚举",那么。。。

public class ProfilePics : System.Collections.IEnumerable
{
    public string status { get; set; }
    public string filename { get; set; }
    public bool mainpic { get; set; }
    public string fullurl { get; set; }
    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
    {
        yield break;
    }
}

它不枚举任何内容,但它是可枚举的。

现在我试着进行一些读心术,想知道你是否想要这样的东西:

public class ProfilePicture
{
    public string Filename { get; set; }
}
public class ProfilePics : IEnumerable<ProfilePicture>
{
    public List<ProfilePicture> Pictures = new List<ProfilePictures>();
    public IEnumerator<ProfilePicture> GetEnumerator()
    {
        foreach (var pic in Pictures)
            yield return pic;
        // or simply "return Pictures.GetEnumerator();" but the above should
        // hopefully be clearer
    }
}

问题是:您想枚举什么?

我想你想要某种容器,里面有你的ProfilePics类型的物品,所以用吧

List<ProfilePics>

在这样的类中:

public class ProfilePic
{
    public string status { get; set; }
    public string filename { get; set; }
    public bool mainpic { get; set; }
    public string fullurl { get; set; }
}
public class ProfilePics : IEnumerable<ProfilePic>
{
    private pics = new List<ProfilePic>();
    // ... implement the IEnumerable members
}

或者只需在需要容器的地方简单地使用List<ProfilePics>

如果你错过了:这是这个IEnumerable的MSDN Docu(还有更多的例子)

要成为可枚举类,应该实现一些集合。在您的示例中,我看不到任何集合属性。如果你想收集个人资料图片,请将你的类重命名为"ProfiePic"并使用List。

如果要将某些属性公开为集合,请将其类型设置为IEnumerable或List或其他集合。

我会使用一个没有继承的类:

using System;
using System.Collections.Generic;
namespace EnumerableClass
{
    public class ProfilePics
    {
        public string status { get; set; }
        public string filename { get; set; }
        public bool mainpic { get; set; }
        public string fullurl { get; set; }
        public IEnumerator<object> GetEnumerator()
        {
            yield return status;
            yield return filename;
            yield return mainpic;
            yield return fullurl;
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            ProfilePics pic = new ProfilePics() { filename = "04D2", fullurl = "http://demo.com/04D2", mainpic = false, status = "ok" };
            foreach (object item in pic)
            {
                Console.WriteLine(item);
                //if (item is string) ...
                //else if (item is bool) ...
            }
        }
    }
}