日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無(wú)先后,達(dá)者為師

網(wǎng)站首頁(yè) 編程語(yǔ)言 正文

C#快速實(shí)現(xiàn)IList非泛型類(lèi)接口的自定義類(lèi)作為數(shù)據(jù)源_C#教程

作者:河西石頭 ? 更新時(shí)間: 2023-04-07 編程語(yǔ)言

使用可以綁定數(shù)據(jù)源的控件我們需要有實(shí)現(xiàn)了IList接口的類(lèi)作為數(shù)據(jù)源,我們有很多的方法,比如使用ArrayList或者List的泛型類(lèi)都是很方便的,或者不怕麻煩的索性直接上DataTable。
但我們也許想實(shí)現(xiàn)一個(gè)專(zhuān)用于某個(gè)自己定義的對(duì)象的list類(lèi),這樣其他類(lèi)想錯(cuò)誤的加入這個(gè)list都不可能了。

一、利用VS的修補(bǔ)程序快速繼承IList

假定我有一個(gè)Creature的類(lèi),如果我們直接在上面加上接口的繼承,則會(huì)出現(xiàn)報(bào)錯(cuò)提示,如下圖:

在這里插入圖片描述

說(shuō)明,這些接口成員都是必須實(shí)現(xiàn)的。
我們來(lái)一一實(shí)現(xiàn),其實(shí)也不必要,因?yàn)槲覀冎皇墙栌盟慕涌谧孋reature類(lèi)成為一個(gè)可以充當(dāng)數(shù)據(jù)源DataSource的類(lèi)。

我們點(diǎn)擊最下面的顯示可能的修補(bǔ)程序(Alt+Enter即可),然后點(diǎn)預(yù)覽,可以根據(jù)自己的需要修改。

在這里插入圖片描述

如果不需要特別的修改,基本直接應(yīng)用即可,只是不能應(yīng)用到數(shù)據(jù)源綁定上。表面上看這樣這個(gè)類(lèi)就實(shí)現(xiàn)了IList接口了,但要用于數(shù)據(jù)源綁定就必須實(shí)現(xiàn)我所列出的5個(gè)成員,否則還是不能做為數(shù)據(jù)源給控件使用。

二、實(shí)現(xiàn)必須的成員

   #region 做數(shù)據(jù)綁定必須實(shí)現(xiàn)的成員

        /// <summary>
        /// 添加元素必須的方法
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public int Add(object? value)
        {
            list.Add(value);
            return list.Count;
            //throw new NotImplementedException();
        }
        public int Count { get { return list.Count; } }
        public object? this[int index] { 
            get { return list[index]; }
            set  { list[index] = value; }
             }
        /// <summary>
        /// 如果要作為DataGridView的數(shù)據(jù)源,必須實(shí)現(xiàn)這個(gè)屬性
        /// </summary>
        public bool IsReadOnly { get { return false;}
        }
        /// <summary>
        /// 迭代必須的方法
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public IEnumerator GetEnumerator()
        {
            return list.GetEnumerator();
            //throw new NotImplementedException();
        }
        #endregion

我們來(lái)看看效果:

在這里插入圖片描述

這里我們測(cè)試了三種綁定數(shù)據(jù)源的控件,分別是ListBox,ComboBox,DataGridView ,沒(méi)有發(fā)現(xiàn)任何問(wèn)題,是不是特別的容易!

原文鏈接:https://haigear.blog.csdn.net/article/details/128771648

欄目分類(lèi)
最近更新