ListBox, list of different objects implementing th

2019-05-10 19:29发布

问题:

I have two objects: User and Client, both implements interface IMember

interface IMember
{
     int Id { get; set; }
     string Name { get; set; }
}

In a form I set ListBox data source:

myListBox.DisplayMember = "Name";
myListBox.ValueMember = "Id";
myListBox.DataSource = membersList; // List<IMember>

And wierd things happen ;) When I run program the first object, whichis type of User, displays correctly (Adrian Serafin) and other objects, wich are type of Contact are displayed like this:

MyProject.Client#20
MyProject.Client#40

as for display was ToString() call on them.

I can't using list of different objects implementing the same interface as datasource in ListBox or I made some mistake here?

回答1:

Are you sure it is List<IMember>, and not ArrayList? This makes a big difference, as the existence of a non-object public indexer (public SomeType this[int] {get;set;}) makes a big difference. The following works fine:

using System;
using System.Collections.Generic;
using System.Windows.Forms;
interface IMember
{
    int Id { get; set; }
    string Name { get; set; }
}
class Foo : IMember
{
    public int Id { get; set; }
    public string Name { get; set; }
}
class Bar : IMember
{ // explicit, why not...
    int IMember.Id { get; set; }
    string IMember.Name { get; set; } 
}
static class Program
{
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        IMember bar = new Bar();
        bar.Id = 2;
        bar.Name = "def";
        var list = new List<IMember> {
            new Foo { Id = 1, Name = "abc"},
            bar,
        };
        Application.Run(new Form
        {
            Controls = {
                new ListBox {
                    Dock = DockStyle.Fill,
                    DisplayMember = "Name",
                    ValueMember = "Id",
                    DataSource = list
                }
            }
        });

    }
}


回答2:

Members are property of class Event:

    [ActiveRecord("cpa_events")]
public class Event : ARBase<Event>
{
         private IList<Interfaces.IMember> _members = new List<Interfaces.IMember>();
         [HasManyToAny(typeof(Interfaces.IMember),"event_id","cpa_events_members",       typeof(int), "member_type", "member_id", MetaType=typeof(string))]
         [Any.MetaValue("User", typeof(User))]
         [Any.MetaValue("Client", typeof(Client))]
         public IList<Interfaces.IMember> Members
         {
            get { return _members; }
            set { _members = value; }
         }
    }

I'm using AR so members list has to be IList and underneath isn't List but NHibernate.Collection.Generic.PersistentGenericBag[Interfaces.IMember]. Is this making a difference?



标签: c# listbox