如何遍历对象,因为foreach不能与对象一起使用。 [英] How to iterate through the object as foreach cannot be used with objects.

查看:98
本文介绍了如何遍历对象,因为foreach不能与对象一起使用。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace oops1
{
    class Program
    {
        static void Main(string[] args)
        {

            string strdetail = "Anurag Nayak 8585916787";
            B b1 = new B();
            object obj= b1.Split(strdetail);

        }
    }
    class B
    {

        public object Split(string str)
        {

            String[] strarray = new String[3];
            strarray = str.Split(' ');

            API p = new API();
            p.firstname = strarray[0];
            p.lastname = strarray[1];
            p.mobilenumber = strarray[2];
            return p;

        }


    }
}










---I return an object from Split function.
--- object obj= b1.Split(strdetail);

How to iterate through the obj.
-- I was trying foreach. But foreach cannot be used with objects. 

Kindly suggest

推荐答案

试试这个





Try this


string strdetail = "Anurag Nayak 8585916787";
           B b1 = new B();
           object obj = b1.Split(strdetail);
           API api = obj as API; // casting the object to Type API
           string firstname = api.firstname;
           string lastname = api.lastname;
           string mobieno = api.mobilenumber;


B类似乎多余的,您可以将其简化为:



Class B seems redundant, you could simplify this to something like:

namespace oops1
{
    class Program
    {
        static void Main(string[] args)
        {

            string strdetail = "Anurag Nayak 8585916787";
            string[] details = strdetail.Split(' ');
            API p = new API(details);
        }
    }


   public class API
   {
       public string Firstname
       {
           get;
           set;
       }
       public string Lastname;
       {
           get;
           set;
       }
       public string Mobilenum;
       {
           get;
           set;
       }

       public API(string [] details)
       {
           Firstname = details[0];
           Lastname = details[1];
           Mobilenum = details[2];
       }
    }
}



您现在可以打印任何字段,例如


You can now print any of the fields with a statement such as

Console.WriteLine("name is: {0} {1}", p.Firstname, p.Lastname);


当拆分返回时,为什么需要将其转换为对象 数组字符串



试试这个



Why do you need to convert it into object when the split returns array string.

Try this

string strdetail = "Anurag Nayak 8585916787";
B b1 = new B();
string[] str= b1.Split(strdetail);





然后使用迭代使用如下: -





then to use iteration use like this:-

for(int i=0;i<str.length;i++)>
{
    //do your work
}


这篇关于如何遍历对象,因为foreach不能与对象一起使用。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆