How to write a method that can output data from any class using generics?

I am trying to write my own method to populate a ListView control with Generics:

    private void BindDataToListView(List<T> containerItems)
    {
        this.View = View.Details;
        this.GridLines = true;
        this.FullRowSelect = true;

        if (this.Items.Count > 0)
            this.Items.Clear();

        this.BeginUpdate();

        int i = 0;
        foreach (T item in containerItems)
        {
            // do something
        }

        this.EndUpdate();
    }

The containerItems parameter can have many elements since I use generics. But I'm stuck in the foreach loop. How to access values ​​in containers?

Should I use reflection for every instance of T in the foreach loop? I think I want to restore the property name. But as soon as I got a property name of type T, how do I get the value?

+3
source share
6 answers

( winforms) - TypeDescriptor; DataTable , ; "" ( IListSource, ITypedList .., : :

PropertyDescriptorCollection props = TypeDescriptor.GetProperties(typeof(T));

:

PropertDescriptor prop = props[propName];

(sourceObject):

object val = prop.GetValue(sourceObject);

( ):

string s = prop.Converter.ConvertToString(val);
+2

T .

+2

T?
, , ... .

, , IListViewBindable - . "CreateListViewItem".

, T , , T IListViewBindable, :

public void BindDataToListView<T>( List<T> containerItems ) where T : IListViewBindable
{}

BindDataToListView :

foreach( T item in containerItems )
{
    this.Items.Add (item.CreateListViewItem());
}
+1

, object. GetType(), . GetProperties(), PropertyInfo. GetValue(), .

, GetProperty(), :

string valueAsString = item.GetType().GetProperty("Something")
                         .GetValue(item, null).ToString();
0

, , , . , , , .

,

object o;
PropertyInfo info = o.GetType().GetProperty().GetProperty("NameOfPropertyIWant");

object value = info.GetValue(o, null);

, ,

public interface IHasThePropertyIWant {
    object NameOfPropertyIWant { get; }
}

void BindDataToListView(List<T> containerItems) where T : IHasThePropertyIWant

,

foreach (T item in containerItems) {
    object o = item.NameOfPropertyIWant;
    // do something with o
}  
0

ObjectListView , , : ListView . , . , .

, Marc () .

0

Source: https://habr.com/ru/post/1714168/


All Articles