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

旧巷老猫 提交于 2019-12-11 18:50:10

问题


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));
    }

回答1:


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.




回答2:


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.




回答3:


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).



来源:https://stackoverflow.com/questions/24983198/how-to-handle-type-object-system-collections-generic-listobject

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!