c#2.0 generics

Source: Internet
Author: User

1. Generic class

Defined:

Class Test<t> Note: T is placeholder can be written casually
{
public T data; Note: Define a field of type T
Public Test (t obj) Note: Defines a method of type T
{
This.data = obj;
}
}

Instantiating a generic class

private static void Main (string[] args)
{
test<int> test = new test<int> (3);
Console.WriteLine (Test.data);

Console.readkey ();
}

2. Generic methods

Defined:

public static void swap<t> (Ref t A, ref T B) value: Defines a generic method, ref refers to whether the reference return value is stored as a reference for the caller to be modified by the local
{
A = b;
}

private static void Main (string[] args)

{

int a = 1;
int b = 2;
swap<int> (ref a, ref B); Note: Pass two values of type int
Console.Write (a);

Console.readkey ();
}

3. Generic constraints

public static void swap<t> (Ref t A, ref T B) where t:struct Note: Delivery type must be a value type
{
A = b;
}

public static void swap<t> (Ref t A, ref T B) where T:class Note: The delivery type must be a reference type
{
A = b;
}

public static void swap<t> (Ref t A, ref T B) where t:new () Note: The pass-type parameter must have a common constructor with no parameters. When used with other constraints, thenew () constraint must be specified last.
{
A = b;
}

public static void swap<t> (Ref t A, ref T B) where t:< base class name > Note: The pass-type parameter must be the specified base class or derived from the specified base class.
{
A = b;
}

public static void swap<t> (Ref t A, ref T B) where t:< interface name > Note: The pass-type parameter must be the specified interface or implementation of the specified interface. You can specify multiple interface constraints. The constraint interface can also be generic.
{
A = b;
}

public static void swap<t> (Ref t A, ref T B) where T:u Note: The type parameter provided for T must be a parameter supplied for u or a parameter derived from U. This is called a bare type constraint.
{
A = b;
}

c#2.0 generics

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.