简体   繁体   中英

Accessing members of an object in array

My question is related to arrays in c#, or what I think is an array. I have a good knowledge in the basics of c# but not much after that.

I have been tasked to make changes to a piece of code below. The code retrieves a list of records from a web service and stores them in what I might be wrongly thinking is an array. Im not sure if arrays can have keys or "columns" like below (PurchaseDate, Location etc..). If not an array what is it?

OO_WebService.Sale[] saleList= OO_webService_connection.GetSales().Sales;

Console.Writeline(saleList[0].PurchaseDate);
Console.Writeline(saleList[0].Location);

Console.Writeline(saleList[1].PurchaseDate);
Console.Writeline(saleList[1].Location);

I also need to print out all keys or column names. For example there are another 20 keys along with PurchaseDate and Location. I want to be able to print out all key names(PurchaseDate) along with their values(01/04/2014 etc..) using a for loop, for example. I know it is possible in javascript. I have tried a few times but had no luck implementing it. Any suggestions greatly appreciated.

You need to use reflection...

var props = saleList.GetType().GetElementType().GetProperties();

foreach (var sale in saleList)
{
    foreach (var p in props)
    {
        Console.WriteLine(p.Name + "=" + p.GetValue(sale,null));
    }
    Console.WriteLine();
}

The array in this case contains Sale elements. An array in C# is just a fixed-size collection of elements, and can contain either primitive types (such as int[] which you may be familiar with) or objects which is the case you're dealing with.

Instead of referring to saleList[0].PurchaseDate , you could rewrite that code as:

for (int i = 0; i < saleList.Lenght; i++)
{
    OO_WebService.Sale sale = saleList[i];
    Console.WriteLine(sale.PurchaseDate);
    Console.WriteLine(sale.Location);
}

So each element, accessed by saleList[ index ] is an instance of the Sale class. I hope that clears things up for you.

You could use right-click on Sale and in the menu select 'Go To Definition'. That will give you all the properties. If Sale is dynamic (eg, can have more or less properties at a later time), you can use reflection (as Tim said). This can be done as follows:

Type type = typeof(Sale);
PropertyInfo[] info = type.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly);
foreach (var i in info)
{
    Debug.WriteLine(i.Name + " = " + i.GetValue(this, null));
}

Note that the return value of GetValue is object and maybe needs to be casted to the correct type. Debug.WriteLine will call the objects default ToString() implementation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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