首頁  >  文章  >  後端開發  >  C# where泛型約束

C# where泛型約束

黄舟
黄舟原創
2017-02-17 11:25:281482瀏覽

        最近無意中看到了:http://www.php.cn/。但是,人笨啊,木有看懂到底是啥意思,木辦法自己寫一個試試看吧,權當做個筆記C# where泛型約束

例子如下:

接口:


介面實作:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace WhereTest
{
    /// <summary>
    /// 水果接口
    /// </summary>
    public interface IFruit
    {
        //水果名称
        string FruitName
        {
            get;
            set;
        }

        string GetName();

        /*接口中只能包含方法、属性、索引器和事件的声明。
         * 不允许声明成员上的修饰符,即使是pubilc都不行,因为接口成员总是公有的,也不能声明为虚拟和静态的。
         * 如果需要修饰符,最好让实现类来声明。
        */
    }
}

創建一個有泛型限制的類別:



,T的型別只能是繼承自IFruit介面的類別。



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace WhereTest
{
    /// <summary>
    /// 梨子类
    /// </summary>
    public class Peach : IFruit
    {
        //无参、公共 构造函数
        public Peach()
        {
        }
        private string fruitName;
        string IFruit.FruitName
        {
            get
            {
                return this.ToString(); ;
            }
            set
            {
                fruitName = value;
            }
        }
        string IFruit.GetName()
        {
            return string.IsNullOrEmpty(fruitName) ? "木有找到名字" : fruitName;
        }
    }
}


運作結果:


)追蹤 


陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn