对实现对象的 ienumerable 的控件使用相同的函数

use same function for controls that implement ienumerable of object

我有这个功能,我想用于列表框、氪列表框、组合框、氪组合框、工具条组合框

 Friend Sub RefreshFromOption(ByRef cbo As KryptonComboBox, ByVal key As String)
        Try
            If Not dicOptions.ContainsKey(key) Then Exit Sub
            cbo.Items.Clear()
            cbo.Items.AddRange(dicOptions(key).Split(","))
        Catch ex As Exception
            LogError(ex)
        End Try

        If cbo.Items.Count > 0 Then cbo.SelectedIndex = 0 'cboReligion.FindStringExact("Default")
    End Sub

目前我必须为所有 5 个 winform 组件编写相同的函数,但是有没有办法为所有组件使用一个函数。

我研究了 ienumerable 接口,但没有得到任何工作

因为控件有自己的 Object.Collection 用于 Items 属性 内部定义,您必须使用这些作为参数单独更新它们,如下所示:

    public partial class Form1 : Form
    {
        private readonly IDictionary<string , string> _dictionary;
        private readonly ComboBox _comboBox;
        private readonly ToolStripComboBox _toolStripComboBox;
        private readonly ListBox _listBox;

        public Form1()
        {
            InitializeComponent();

            _comboBox = new ComboBox();
            _toolStripComboBox = new ToolStripComboBox();
            _listBox = new ListBox();

            _dictionary = new Dictionary<string , string>();

            UpdateControls( 
                "test" , 
                new ListControl[] { _comboBox , _toolStripComboBox.ComboBox , _listBox } ,
                new IList[] { _comboBox.Items , _toolStripComboBox.Items , _listBox.Items } );
        }

        private void UpdateControls( string key , IEnumerable<ListControl> listControls , IEnumerable<IList> itemCollections )
        {
            var items = GetItems( key ).ToArray();
            if ( items.Length > 0 )
            {
                UpdateItemsCollection( items , itemCollections );
                UpdateSelectedIndex( listControls );
            }
        }

        private static void UpdateSelectedIndex( IEnumerable<ListControl> listControls )
        {
            foreach ( var listControl in listControls )
            {
                listControl.SelectedIndex = 0;
            }
        }

        private static void UpdateItemsCollection( object[] objects , IEnumerable<IList> objectCollections )
        {
            foreach ( var objectCollection in objectCollections )
            {
                objectCollection.Clear();
                foreach ( var obj in objects )
                {
                    objectCollection.Add( obj );
                }
            }
        }

        private IEnumerable<object> GetItems( string key )
        {
            if ( _dictionary.ContainsKey( key ) )
            {
                return _dictionary[key].Split( ',' );
            }
            return null;
        }