A question about generic Constraints

Source: Internet
Author: User

This article is based on the book 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

}

}

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 ()

}

----------------------- The following are test classes -----------------------------

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 );

}

}

The purpose of the test class is to plan the sum of the two Area numbers of the Rect and Circle, but this code compilation will not pass, because during the real-listed Circle and Rect, the generic type does not know the existence of the Area attribute, contact must be implemented. The code can be modified

Public double TotalArea

{

Get

{

Double acc = 0;

{

Forearch (T shape in shapes)

{

IShape theShape = (IShape) shape; // Add a knot

Acc + = shape. Area;

} Return acc;

}

}

To ensure that all types of T have the "Area" type, you can add "Contact" to the class definition and write it as public class Shapes. Where T: The T type such as IShape must implement the IShape interface; otherwise, the compilation fails.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.