Lost !

-----hard working for the furture.

导航

统计

C#泛型学习笔记之一(约束)

泛型可以使代码重用率提高

泛型需要编译器解决类型安全并降低装箱拆箱引发的性能损耗

泛型给编译器带来的问题:约束

约束分为:

1.一般约束

T Find(K key)
{
   Node current = m_Head;
   while(current.NextNode != null)
   {
      if(current.Key == key) //编译将不能通过
         break;
      else
         current = current.NextNode;
   }
   return current.Item;
}

以上编译错误是因为编译器无法保证Key类中包含==操作而引发

若要避免可将代码加上约束where 关键字,此关键字等于告诉编译器K实现了Icomparable的接口,附带的好处是将会在此类中为K类型的变量提供智能提示。

public class LinkedList where K : IComparable
{
   T Find(K key)
   {
      Node current = m_Head;
      while(current.NextNode != null)
      {
         if(current.Key.CompareTo(key) == 0)
           
            break;
         else     
           
            current = current.NextNode;
      }
      return current.Item;
   }
   //Rest of the implementation
}

可以为某个类提供多个约束

public class LinkedList where K : IComparable
                             where T : ICloneable

{...}

2.派生约束

可以为某个子类K提供派生约束如下
public class MyBaseClass
{...}
public class LinkedList where K : MyBaseClass
{...}

同样加上where关键字等同于告诉编译器K继承自MyBaseClass类,可以在LinkedList中为K提供智能提示

注意:

在此类约束中必须注意子类以及基类的访问控制

public class MyBaseClass
{}
internal class MySubClass where T : MyBaseClass
{}

是没有问题的。但是,如果这两个类的可见性被颠倒,例如:
internal class MyBaseClass
{}
public class MySubClass where T : MyBaseClass
{}
则编译器会发出错误,因为程序集外部的任何客户端都无法使用一般类型 MySubClass,从而使得 MySubClass 实际上成为内部类型而不是公共类型。外部客户端无法使用 MySubClass 的原因是,要声明 MySubClass 类型的变量,它们需要使用派生自内部类型 MyBaseClass 的类型。

3.构造函数约束

class Node where T : new()
{
   public K Key;
   public T Item;
   public Node NextNode;
   public Node()
   {
      Key      = default(K);
      Item     = new T();
      NextNode = null;
   }
}

加上new()关键字,等同于告诉编译器T类型一定包含有无参数的(默认的)构造函数。

可以将构造函数约束与派生约束组合起来,前提是构造函数约束出现在约束列表中的最后:

public class LinkedList where K : IComparable,new()
{...}

 

 

MSDN上泛型的介绍:http://msdn2.microsoft.com/zh-cn/library/ms379564(vs.80).aspx#EWAA

以及示例:下载GenericsInCSharp.msi 示例文件

posted on   失落''80  阅读(91)  评论(0编辑  收藏  举报

编辑推荐:
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?
点击右上角即可分享
微信分享提示