Warm tip: This article is reproduced from stackoverflow.com, please click
c# object

How to retrieve values from object in c#?

发布于 2020-03-31 22:59:04

I have a method Test which stores strings in a list. That list is passed to another method which accepts object. Below is the code. Now, I want to retrieve 2,3 and 4,5 from object.

public static void Test()
        {
            List<string> list = new List<string>();
            list.Add("2,3");
            list.Add("4,5");
            Test1(list);
        }

public static void Test1(object obj)
        {
           //How to get the values from object. I want to retrieve 2,3 and 4,5.
        }
Questioner
Asit Sahoo
Viewed
38
Krishna Muppalla 2020-02-01 19:16

You can iterate the obj using foreach

public static void Test1(object obj)
{
    foreach(var value in (List<string>)obj)
    {
        Console.WriteLine(value);
    }
}

However, I suggest changing the parameter object to List<string>

public static void Test1(List<string> listValues)
{
    foreach(var value in obj)
    {
        Console.WriteLine(value);
    }
}