如何将类型受约束的对象添加到列表框 [英] How to add type constrained objects to listbox

查看:62
本文介绍了如何将类型受约束的对象添加到列表框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

方法标题如下

public void Deletetorpedo(List< CTorpedo> torpList)
{
}

我们尝试实例化该类,然后使用该实例来访问我们要使用的列表.

TorpedoCSVProvider torpedos =新的TorpedoCSVProvider();

问题在于对象列表只能通过ref访问,因为从文件读取后填充列表的方法将返回返回代码,以确认读取是否成功.

int retCode = torpedos.GetTorpedo(ref torpList);

根据我们的理解,这意味着"torpList"已通过我们传递给的方法进行了更改.这是我们要出问题的地方吗?因为稍后当我们尝试将列表中的对象添加到列表框中时,没有任何显示.

因此,请帮助我们强制转换这些对象并填充列表.

The method header is as follows

public void Deletetorpedo(List<CTorpedo> torpList)
{
}

We''ve tried instantiating the class, then using the instance to gain access to the list we want to use.

TorpedoCSVProvider torpedos = new TorpedoCSVProvider();

The problem is the list of objects can only be accessed through a ref, because the method that populates the list after reading from the file returns a return code to confirm whether the read went succesfully or not.

int retCode = torpedos.GetTorpedo(ref torpList);

From our understanding that means "torpList" has now been changed by the method we passed it through to. Is this where we are going wrong? because later when we try to add the objects in the list to the listbox... nothing shows up.

So please help us with the casting of these objects and populating the list.

推荐答案

如果我了解您要添加的内容...

由于ListBoxItems集合是object类型的集合,因此在将对象添加到ListBox时不必强制转换对象.只需将此方法添加到您的商品类中即可:

If I understand what you''re aslking...

Since the ListBoxItems collection is a collection of type object, you don''t have to cast the object when you add it to the ListBox. Just add this method to your item class:

public override string ToString()
{
    // assuming desiredProperty is a string
    return desiredProperty;
}



现在,您只需将项目添加到列表框中,列表框将使用ToString()返回的任何内容来显示项目.

使用ListBox.SelectedItem时,需要将其强制转换为适当的类型(对于您的情况,TorpedoSvcProvider我怀疑:



Now, you can simply add your items to the listbox, and the listbox will use whatever is returned by ToString() for displaying the items.

When you use ListBox.SelectedItem, you will need to cast that to the appropriate type (in your case, TorpedoSvcProvider I suspect:

TorpedoSvcProvider selected = listBox1.SelectedItem as TorpedoSvcProvider;


只有一个问题:您可以将任何对象添加到列表项,但是当您执行此操作时,UI中将显示什么?答案是:无论存在什么虚方法ToString的相应实现,都会返回.因此,您需要重写此方法以在
There is just one problem: you can add any objects to the list items, but what will be shown in UI when you do it? The answer is: whatever there respective implementations of the virtual method ToString returns. Therefore, you need to override this method to show desired strings in the
ListBox<code> control.<br />
<br />
<dd>—SA</dd>


这篇关于如何将类型受约束的对象添加到列表框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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