c#2.0 Generic Learning--Introductory articles

Source: Internet
Author: User
Tags abstract define constructor implement inheritance reference tostring
Recent frequent exposure to generic aspects of the problem, so also have to learn, began mainly in the MSDN webcast up to download teaching video (Li Jianzhong teacher), this article first introduce the knowledge of generics, I hope that the beginning to learn generic friends can be faster to get started, To start with, let's take a look at the basic concepts of generics:
The most significant point is that it has parameterized types, abstract the type as a parameter, so that we can better implement the reuse of the code in the actual application, while it provides a stronger type of security, higher efficiency, but in terms of constraints, it only supports the display of constraints, This is not as good in terms of flexibility. I think it can provide more efficiency because generics take the "On-demand" pattern when instantiated, on-demand instantiation occurs when JIT (Just in time) compiles.
Here's how to define a generic class, and it's simple, you just have to realize that, here, the type has been parameterized: using System;
Using System.Collections.Generic;
Using System.Text;

Namespace Generictest
{
Class Program
{
static void Main (string[] args)
{
Using String,int to instantiate test<t,s> classes
test<string, int> t = new test<string, int> ("SHY520", 22);

Calling methods in a generic class
T.setvalue ();
}
}

/**////<summary>
Defines a generic class that has two type parameters, respectively, t,s
Http://pw.cnblogs.com
</summary>
<typeparam name= "T" > Type parameters </typeparam>
<typeparam name= "S" > Type parameters </typeparam>
public class Test<t,s>
{
The type parameters of a generic class are available for class members
private T name;
Private S age;

Public Test (T name,s Age)
{
THIS.name = name;
This.age = age;
}

public void SetValue ()
{
Console.WriteLine (name. ToString ());
Console.WriteLine (age. ToString ());
}
}
}


The above example is not very appropriate, the purpose is to let beginners of generics you understand the definition of generics and the instantiation method, as above, we have defined a generic class, then how to implement the generic class inheritance? Here you need to meet any of the following two points:
1. In generic class inheritance, the parent class's type parameter has been instantiated, which does not necessarily have to be a generic class;
2, the type parameter of the parent class is not instantiated, but comes from subclasses, that is, the parent class and subclass are generic classes, and both have the same type parameters;

If you write this, you'll obviously report that you can't find the type T,s error
public class Testchild:test<t, s> {}

The correct wording should be
public class testchild:test<string, int>{}

public class Testchild<t, s>: Test<t, s> {}

public class Testchild<t, s>: Test<string, int> {}
Then we look at the generic interface, which is created and inherited by the same rules as the generic class above, look at the following code:
public interface ilist<t>
{
T[] GetElements ();
}
public interface idictionary<k,v>
{
void Add (K key, V value);
}

The type parameter of the generic interface is either instantiated
Either from the type parameter that implements the class declaration
Class list<t>: Ilist<t&gt, Idictionary<int, t>
{
Public t[] GetElements () {return null;}
public void Add (int index, T value)
{
}
}

Looking at a generic delegate, we first define a delegate with a type parameter of T, and then invoke the method in the class using the delegate:
Using System;
Using System.Collections.Generic;
Using System.Text;

Namespace Generictest
{
Define a delegate, type parameter is T, return value type T
Generic delegates support the application of type parameters on return values and parameters
Delegate string genericdelete<t> (T value);

Class Test
{
static string F (int i) {return "SHY520";}
static string G (string s) {return "SHY520";}

static void Main (string[] args)
{
genericdelete<string> G1 = G;
genericdelete<int> G2 = new genericdelete<int> (F);
}
}
}


Let's look at the generic method again, and the generic mechanism of C # only supports the inclusion of type parameters on the method declaration, which is the generic method. It is particularly noted that generics do not support the use of type parameters on other class/interface members other than methods, but they can be contained in generic types and can use the type parameters of generic types. It is also important to say that a generic method can exist in a generic type or in a non-generic type. Let's take a look at the declarations, invocations, overloads, and overrides of the generic type respectively.

Using System;
Using System.Collections.Generic;
Using System.Text;

Namespace Generictest
{
Class Genericclass
{
Declare a generic method
Public T getvalue<t> (T-t)
{
return t;
}

Calling a generic method
Note: When calling a generic method, instantiate the type parameter of the generic method
public int Usemethod ()
{
Return this.getvalue<int> (10);
}

Overloaded GetValue method
public int GetValue (int i)
{
return i;
}
}

The following demo overrides
Note that when a generic method is overridden, the constraint is inherited by default, and the constraint relationship does not need to be specified again
Abstract class Parent
{
Public abstract K test<k, v> (k K, v v) where k:v;

}

Class Child:parent
{
public override T Test<t, s> (T-T, s)
{
return t;
}
}
}


Finally, let's take a look at the constraints in generics:
Generics in C # support only the displayed constraints, because this guarantees the type safety required by C #, but the displayed constraint is not necessary and, if not constrained, the generic type parameter will only be able to access the public method in the System.Object type. An explicit constraint is expressed by a WHERE clause that specifies a base class constraint, an interface constraint, a constructor constraint, a value type/reference type constraint, and a total of four constraints. The following example comes from the lecture ppt of teacher Li Jianzhong.
1. Base class constraint:

Class A {public void F1 () {}}
Class B {public void F2 () {}}
Class c<s,t>
where s:a//S inherits from A
where t:b//T inherits from B
{
You can call F1 on a variable of type S,
You can call F2 on a variable of type T
}
2, interface constraints
Interface iprintable {void Print ();
}
interface icomparable<t> {int CompareTo (T v);}
Interface Ikeyprovider<t> {T getkey ();}
Class dictionary<k,v>
where k:icomparable<k>
where v:iprintable, ikeyprovider<k>
{
You can call CompareTo on a variable of type K,
You can call print and getkey on a variable of type V
}
3, constructor constraints
Class A {public A () {}}
Class B {public B (int i) {}}
Class c<t>
where T:new ()
{
The T t=new T () can be used in it;
}
C<a> c=new c<a> (); OK, A has a parameterless constructor
C<b> c=new c<b> (); Error, b no parameterless constructor
4, Value/reference type constraint
public struct A {}
public class B {}
Class c<t>
where t:struct
{
T is a value type inside this
}
C<a> c=new c<a> (); Yes, A is a value type
C<b> c=new c<b> (); Error, B is a reference type


About C # generics getting started with so much knowledge, I am also to Li Jianzhong Teacher's teaching video to learn, beginners friends can also go to download video to see:

http://www.microsoft.com/china/msdn/events/webcasts/shared/webcast/episode.aspx?newsID=1242246

Learning generics is just beginning, I hope to have expert advice, thank you!

Email:pwei013@163.com



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.