zoukankan      html  css  js  c++  java
  • 泛型接口

    1,使用泛型接口的好处:

      1)提供出色的编译时类型安全;有的接口(比喻非泛型接口 ICompareable)定义的方法有object参数或返回类型,当代码调用这些接口方法时,可以传递对任何对象的引用,但这不是我们期望的;

     

     1private void SomeMethod1() 
     2{
     3Int32 x = 1, y = 2;
     4IComparable c = x;
     5// CompareTo expects an Object; passing y (an Int32) is OK
     6c.CompareTo(y); // Boxing occurs here
     7// CompareTo expects an Object; passing "2" (a String) compiles
     8// but an ArgumentException is thrown at runtime
     9c.CompareTo("2");
    10}

       显然,理想的是让接口方法接受强类型,基于这个原因,FCL 中包含一个泛型接口IComparable<T>.

      

    Code

       2) 操作值类型,不需要太多的装箱;

       3)类可以实现同一个接口若干次,只要使用不同的类型参数。

     

     1using System;
     2// This class implements the generic IComparable<T> interface twice
     3public sealed class Number: IComparable<Int32>, IComparable<String> 
     4{
     5   private Int32 m_val = 5;
     6   // This method implements IComparable<Int32>'s CompareTo
     7   public Int32 CompareTo(Int32 n) {
     8   return m_val.CompareTo(n);
     9}

    10// This method implements IComparable<String>'s CompareTo
    11public Int32 CompareTo(String s) 
    12  {
    13   return m_val.CompareTo(Int32.Parse(s));
    14  }

    15}

    16public static class Program 
    17{
    18   public static void Main() 
    19  {
    20     Number n = new Number();
    21     // Here, I compare the value in n with an Int32 (5)
    22     IComparable<Int32> cInt32 = n;
    23    Int32 result = cInt32.CompareTo(5);
    24    // Here, I compare the value in n with a String ("5")
    25    IComparable<String> cString = n;
    26   result = cString.CompareTo("5");
    27   }

    28}

  • 相关阅读:
    Linux运维必会的MySql题之(四)
    Linux运维必会的MySql题之(三)
    Linux运维必会的MySql题之(二)
    Linux运维必会的MySql题之(一)
    Centos7 yum安装Mysql
    Devoos核心要点及kubernetes架构概述
    kubernetes基本概念
    BZOJ2631 tree 【LCT】
    BZOJ2431 [HAOI2009]逆序对数列 【dp】
    BZOJ1483 [HNOI2009]梦幻布丁 【链表 + 启发式合并】
  • 原文地址:https://www.cnblogs.com/Rufy_Lu/p/1397756.html
Copyright © 2011-2022 走看看