简体   繁体   中英

How to handle type “Object {System.Collections.Generic.List<object>}”

This is my first time encountering with such an object.

>Link of image of my local window during debug<

So to put it very simply, how do I access the value for CardNO or ItemID, which is 296 and 130 respectively when the only methods 'test' give are exactly like a normal object and I don't know what to cast it to. I can't even do this 'test[0]'.

This is where 'test' comes from:

private void ListBoxIssue_OnDragEnter(object sender, DragEventArgs e)
    {
        var test = DragDropPayloadManager.GetDataFromObject(e.Data, typeof(CommsItem));
    }

Use

var item = (CommsItem)((List<object>)test).FirstOrDefault();

Be sure to check first if test is an instance of List<object> before casting, and if test[0] is an instance of CommsItem.

You need to cast your List<Object> to List<CommsItem> .

Example:

var test = DragDropPayloadManager.GetDataFromObject(e.Data, typeof(CommsItem)).Cast<CommsItem>().ToList();

Or cast each individual element:

CommsItem element = (test[0] as CommsItem);

Which will return the element casted to CommsItem , unless it is not of or derived of that type, in which case it will return null.

So to answer your question, you can access them as:

string CardNO = (test[0] as CommsItem).CardNO;

or

var test = DragDropPayloadManager.GetDataFromObject(e.Data, typeof(CommsItem)).Cast<CommsItem>().ToList();
string CardNO = test[0].CardNO;

(If you use the first method, you do not need the cast)

What you are doing is casting your List<object> , test , to a List<CommsItem> , that you can use to access the properties, or simply casting each item.

More simply:

var item = ((List<object>)test).Cast<CommsItem>().FirstOrDefault();

If your list is not a list of CommsItem , then you'll get an empty list back. FirstOrDefault() ensures that you get the first item only, and if there is no first item, then the default value for the item (for a reference object, this would be null ).

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