zoukankan      html  css  js  c++  java
  • 一个关于泛型约束的问题

    *申明,本文引自 《Accelarated C# 2008》一书 废话不多说,直接看例子

    using System;

    using System.Collections.Generic;

    public interface IShape

    {

      double Area

      {

         get;

       }

     }

    public class Circle : Ishape

    {

      public Circle(double radius)

      {

       this.radius = radius;

       }

       public double Area

      {

        get

          {

             return 3.1415 * radius* radius

           }

       }

      private double radius;

    }

    public class Rect : IShape

    {

      public Rect(double width,double height)

      {

        this.width = width;

        this.height = height;

      }

      public double Area

      {

        get

          {

             return width * height;

          }

      }

      private double width;

      private double height;

    }

    public class Shapes

    {

      public double TotalArea

      {

        get

          {

             double acc = 0

            {

            forearch(T shape in shapes)

            {

              acc +=shape.Area;

            }

          return acc;

          }

      }

      public void add(T shape)

      {

        shapes.Add( shape);

      }

      private List shapes =new List()

      }

    -----------------------以下是测试类-----------------------------

    public class EntryPoint

      {

        static void Main()

        {

          Shapes shapes =new Shapes() ;

          shapes.Add(new Circle(2));

          shapes.Add(new Rect(3,5));

          Console.WriteLine("Total Area :{0}",shapes.TotalArea);

         }

      }

    测试类的目的是计划出Rect,Circle两个面积数字之和,可是这段代码编译不会通过,因为在实列化Circle,Rect的时候,泛型并不知道Area属性的存在,必须实现Contact,代码可修改为

    public double TotalArea

    {

      get

      {

        double acc = 0 ;

        {

          forearch(T shape in shapes)

          {

            IShape theShape =(IShape) shape;//加上结口实现

            acc +=shape.Area;

          } return acc;

        }

    }

    为了确保T类型都有Area属,可以在类定义时就加上Contact,写法为 public class Shapes where T : IShape 这样T类型必须实现IShape结口,否则编译不通过

  • 相关阅读:
    luogu P2570 [ZJOI2010]贪吃的老鼠【二分+最大流】
    luogu P5358 [SDOI2019]快速查询【模拟(?)】
    CF360E Levko and Game【贪心+dijsktra】
    bzoj 2632: [neerc2011]Gcd guessing game【贪心】
    bzoj 2535: [Noi2010]Plane 航空管制2【拓扑排序+堆】
    Amazon免费CE2基于docker部署nginx,并实现访问
    使用FlashFXP,密钥方式连接Amazon的CE2实例
    python 提示 AttributeError: module 'json' has no attribute 'dumps'
    ueditor工具栏新增按钮教程
    Express4+Mongodb超简单入门实例
  • 原文地址:https://www.cnblogs.com/zycblog/p/1612853.html
Copyright © 2011-2022 走看看