.NET 泛型的特殊使用

来源:互联网 发布:qq群淘宝客优惠劵软件 编辑:程序博客网 时间:2024/04/30 01:54

定义泛型的后面加where子句,可以要求,该泛型定义的参数必须满足一定条件:如实现了一定接口,继承自某一基类,具有一个无参构造函数等.

 

using System;
using System.Collections.Generic;
using System.Text;
namespace GenericWhereDemo
{
    
class Program
    
{
        
static void Main(string[] args)
        
{
            ShapeList
<Rectangle> rect = new ShapeList<Rectangle>();
            rect.ShowArea(
new Rectangle(36));
            ShapeList
<Triangle> tri = new ShapeList<Triangle>();
            tri.ShowArea(
new Triangle(36));
            ShapeList
<SolidLine> line = new ShapeList<SolidLine>();
            line.ShowArea(
new SolidLine(5));
            Console.ReadLine();
        }

    }


    
class ShapeList<T> where T : IShape
    
{
        
public void ShowArea(T item)
        
{
            Console.WriteLine(
"Area is {0}", item.Area()); 
        }

    }

    
interface IShape
    
{
        
double Area();
    }

    
class Rectangle : IShape
    
{
        
public double length;
        
public double width;
        
public Rectangle(double length, double width)
        
{
            
this.length = length;
            
this.width = width;
        }

           
        
public double Area()
        
{
            
return this.length * this.width;
        }

    }

    
class Triangle : IShape
    
{
        
public double length;
        
public double height;
        
public Triangle(double length, double height)
        
{
            
this.length = length;
            
this.height = height;
        }

        
public double Area()
        
{
            
return this.length * this.height / 2;
        }

    }

    
class SolidLine
    
{
        
public double length;
        
public SolidLine(double length)
        
{
            
this.length = length;
        }

    }

}

 
 

 

原创粉丝点击