C # typical generic example

Source: Internet
Author: User

 

Function parameters are called polymorphism. Can the parameter types of a function be determined?

Can a function return only one value? Is the return value of the function uncertain?

Generic is a special type that delays the work of a specified type until the client Code declares and instantiates a class or method.

The following are two classic examples:

 

1. Enter a string and convert it to the desired type.

With the wildcard feature, the returned value can be of the specified type.

2. Compare two objects and return a large value.

Using System;

Using System. Collections. Generic;

Using System. Text;

 

Namespace FamilyManage

{

Class CGeneric

{

// Data Conversion

Static public T Convert <T> (string s) where T: IConvertible

{

Return (T) System. Convert. ChangeType (s, typeof (T ));

}

// Take one of the two large numbers

Static public T Max <T> (T first, T second) where T: IComparable <T>

{

If (first. CompareTo (second)> 0)

Return first;

 

Return second;

}

// Use

Static public void test ()

{

//

Int iMax = Max (123,456 );

Double dMax = Max <double> (1.23, 4.56); // you can specify the return type.

//

Int iConvert = Convert <int> ("123456 ");

Float fConvert = Convert <float> ("123.456 ");

//

System. Windows. Forms. MessageBox. Show (iMax + "|" + dMax + "|" + iConvert + "|" + fConvert );

}

}

}

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.