例子以下:
接口:
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都不可,因为接口成员老是公有的,也不能声明为假造和静态的。 * 假如须要修饰符,最好让完成类来声明。 */ } }
接口完成:
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; } } }
建立一个带有泛型束缚的类:
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace WhereTest { /// <summary> /// 带有泛型束缚的类 /// </summary> /// <typeparam name="T"></typeparam> public class FruitMarket<T> where T : IFruit, new()//new()的意义是,这个T必须有public组织函数 { T item = new T(); public void FruitSayHello() { item.FruitName = "我是梨子"; Console.WriteLine("你好:" + string.Format("Fruit:{0}", item.GetName())); Console.ReadKey(); } /*在定义泛型类时,可以对客户端代码可以在实例化类时用于范例参数的范例品种施加限定。 * 假如客户端代码尝试运用某个束缚所不允许的范例来实例化类,则会发生编译时毛病。*/ } }
因为有where字句的泛型束缚,所以,建立FruitMarket的对象时,T的范例只能是继续自IFruit接口的类。
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace WhereTest { class Program { static void Main(string[] args) { //实例化以后 只能在static要领中挪用响应的要领,不然 基础找不着peach变量 FruitMarket<Peach> peach = new FruitMarket<Peach>(); peach.FruitSayHello(); } } }
运转效果:
以上就是C# where泛型束缚的内容,更多相关内容请关注ki4网(www.ki4.cn)!