0

下面是我的课。我需要使其可枚举。我在网上查看过,虽然我找到了很多文档,但我仍然迷路了。我认为这绝对是我第一次要问这个问题,但是有人可以请让这个该死的东西为我枚举,我会从那里弄清楚。我正在使用 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; }

}
4

4 回答 4

2

好吧......如果你想要的只是让某人“让这个该死的东西可枚举”,那就去......

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
    }
}
于 2014-06-25T22:51:49.587 回答
0

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

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) ...
            }
        }
    }
}
于 2014-07-26T19:48:43.613 回答
0

问题是:你想列举什么?

我猜你想要某种容器,包含你的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 文档(还有更多示例)

于 2012-03-20T05:39:56.910 回答
0

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

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

于 2012-03-20T05:40:40.187 回答