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}

  • 相关阅读:
    BZOJ4779: [Usaco2017 Open]Bovine Genomics
    USACO比赛题泛刷
    BZOJ1977: [BeiJing2010组队]次小生成树 Tree
    LOJ #10132. 「一本通 4.4 例 3」异象石
    $O(n+log(mod))$求乘法逆元的方法
    BZOJ2226: [Spoj 5971] LCMSum
    数据库 | Redis 缓存雪崩解决方案
    中间件 | 微服务架构
    数据库 | SQL 诊断优化套路包,套路用的对,速度升百倍
    数据库 | SQL语法优化方法及实例详解
  • 原文地址:https://www.cnblogs.com/Rufy_Lu/p/1397756.html
Copyright © 2011-2022 走看看