简体   繁体   English

将类设置为IEnumerable并获取类型

[英]Set class to IEnumerable and get type

Been searching and trying different things but just can't seem to get it working right. 一直在搜索并尝试不同的东西,但似乎无法使其正常工作。
So, here are the basics... 所以,这是基础知识...

namespace Model
{
  [Serializable]
  public class SomeMDL : IEnumerable<string>
  {
      public int ID { get; set; }
      public int Volumne { get; set; }
      public int Size { get; set; }
  }

    public IEnumerator<string> GetEnumerator()
    {
        yield return ID.ToString();
        yield return Volume.ToString();
        yield return Size.ToString();
    }

    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
    {
        return this.GetEnumerator();
    }
}

Then call the class: 然后调用该类:

        Model.SomeMDL mdl = new Model.SomeMDL();
        mdl.ID = 1;
        mdl.Volume = 2;
        mdl.Size = 2;

        string myVar;            
        foreach (string item in mdl)
        {                
            //myVar = item.GetType().ToString();
            //myVar = item.GetEnumerator().GetType().Name.ToString();
            //myVar = item.GetEnumerator().GetType().FullName.ToString();
            //myVar = item.GetEnumerator().GetType().DeclaringType.FullName.ToString(); //null ref
            myVar= item.ToString(); //gets the value             
        }

What I am looking for is a way not only to bring back the values, which is item.ToString() but I need to know which public int it is reading. 我正在寻找的不仅是一种方法来取回值为item.ToString()的值,而且我还需要知道它正在读取哪个公共int。 Is it ID, Volume, or Size? 是ID,数量还是大小?
Need to bring back a string of the type (ID, Volume, or Size). 需要带回一个类型(ID,音量或大小)的字符串。

Thanks 谢谢

Unless I'm missed something about your code here, it seems like you're misusing/misunderstanding the basic concept of the IEnumerable interface. 除非我在这里不了解您的代码,否则似乎您正在滥用/误解IEnumerable接口的基本概念。 IEnumerable is used to represent a group of objects of the same type, which can then be iterated through. IEnumerable用于表示一组相同类型的对象,然后可以对其进行迭代。 All you're doing is just yielding each of the properties within your class - what is the point? 您要做的只是产生类中的每个属性-意思是什么? If you need any one of the properties, why not just access it normally? 如果您需要任何一个属性,为什么不正常访问它呢? What do you imagine you'll gain by allowing yourself and others to blindly iterate through your three properties? 您认为让自己和他人盲目地遍历这三个属性会获得什么收益?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM