Seeing him, I suddenly realized-generic (2) Introduction to generics (next to the previous article, the specific example will be presented later)

Source: Internet
Author: User

Just write these things. I read an article from the CAO moderator on csdn:Do not know if anyone is willing to participate. To be honest, I have been working for four years, and I always feel dizzy.

Yes, but none of them are proficient. After reading this post, I want to listen to the teachings of the great gods. I want to improve myself because I have no time, and because I am in Beijing. So I didn't sign up.

May not have the opportunity to go ). So I went to the library to develop these concepts. In fact, I hope that the great gods in Beijing can also organize similar activities. I want to respond a lot. In fact, if I want to organize this once

The activity will also be improved. These are what I got from reading a book in the library. Please share them with us.Administrator handsDo not write every article into the Cold palace. I have done it with great care. In addition

If you are interested, you can add my qq348537081. Let's discuss your experiences. Finally, you can contact me for the kids shoes you like to read. The Capital Library is accessible every Saturday.

There are a lot of things to talk about. Let's turn to the subject below. In fact, this articleArticleIs the extension and modification of the generic introduction (followed by the previous article, the specific case is subsequently presented.

Because I cannot connect to the Internet at home, I use WPS to write it in advance. There may be some problems in all formats, so please wait.

2.2Interface constraints (Where t:Interface-name)

To specify that an interface must be implemented for a data type,You need to declareInterface Constraints(Interface constraint ).With this constraint,You do not even need to perform type conversion.,You can call a display interface member to implement.Connect

The main functions of the interface constraints are the same as those of the base class constraints. First, it allows developers to use interface members in generic classes. Second, it ensures that only the type parameters that implement a specific interface can be used. This means that for any given

Port constraints: the type parameter is either the interface itself or the class that implements the interface.

Note: You can use a comma-separated list to specify multiple interfaces at the same time. If a constraint contains both the base class and interface, specify the base class before specifying the interface list.

For example, to ensureTThe type parameters are all preemptible.IcomparableInterface,

Public class binary <t> where T: system. icomparable {...}

The compiler ensures thatBinaryClass,You must specify an implementationIcomparableInterface Type Parameters.

 

The followingProgramRewrite the phone list program in the previous program to explain the purpose of interface constraints. In this program,PhonenumberClass is converted toIphonenumber. Then,FriendAndSupplierThis interface is implemented.

 Class  Notfoundexception1: exception {  Public Notfoundexception1 (): Base  (){}  Public Notfoundexception1 ( String Str ): Base  (STR ){}  Public Notfoundexception1 ( String STR, exception inner ): Base (STR, inner ){}  Protected  Notfoundexception1 (system. runtime. serialization. serializationinfo Si, system. runtime. serialization. streamingcontext SC ):  Base  (Si, SC ){}}  Public   Interface  Iphonenumber {  Public   String Number { Get ; Set  ;} Public   String Name { Get ; Set  ;}}  Public   Class  Friend1: iphonenumber {  Public   String Number { Get ; Set  ;}  Public   String Name {Get ; Set  ;}  Public   Bool Isworknumber { Get ; Set  ;}  Public Friend1 ( String Name, String Num, Bool  WK) {name = Name; number =Num; isworknumber = WK ;}}  Public   Class  Supplier1: iphonenumber {  Public   String Name { Get ; Set  ;}  Public   String Number { Get ; Set ;}  Public Supplier1 ( String Name, String  Num ){  This . Name = Name;  This . Number = Num ;}}  Class  Friendemail1 {}  Class Phonelist1 <t> Where T: iphonenumber {T [] phlist;  Int  End;  Public  Phonelist1 () {phlist = New T [ 10  ]; End = 0  ;}  Public   Bool  Add (T newentry ){  If (END =10 ) Return   False  ; Phlist [end] = Newentry; End ++ ;  Return   True  ;}  Public T findbyname ( String  Name ){  Foreach (T item In Phlist ){  If (Item. Name = Name)  Return  Item ;}  Throw   New  Notfoundexception1 ();}  Public T findbynum ( String  Num ){  Foreach (T item In Phlist ){  If (Item. Number = Num)  Return  Item ;}  Throw   New  Notfoundexception1 ();} 

 

 

 

2.3 struct/classConstraints(Where T: Class/struct)

Another important generic constraint is to restrict a type parameter to a value type or a reference type. The compiler does not allow System. valuetype Specify the base class . Opposite , C # Provides special syntax , This syntax applies to both reference types. . In this syntax , Not T Specify a base class . Opposite , You only need to specify the keyword Struct Or Class. When other constraints exist, Class Or Struct Must start with the constraint list

Example:

Public struct nullable <t>: iformattable, icomparable, icomparable <nullable <t>, inullable where T: struct

{//.......}

2.4 new() Constructor Constraints

New ()Constructor constraints allow developers to instantiate a generic object. Generally, you cannot create an instance with a wildcard parameter. However,New ()The constraint changes this situation and requires that the type of real arguments be required.

Provides a constructor without parameters. In useNew ()You can call the non-argument constructor to create an object.

ClassMyclass {PublicMyclass (){}}ClassTest <t>WhereT:New() {T obj;PublicTest () {OBJ=NewT ();}}

 

Call:

Test <myclass> X = new test <myclass> ();

Note:MyclassYou do not need to explicitly declare a non-parameter constructor. The default constructor can also meet this constraint. However, if you need to define other constructors in addition to constructors without parameters for a class, you must

Explicitly declare constructors without parameters for this class.

UseNew ()Pay attention to the following three points:

1. It can be used with other constraints, but must be at the end of the constraint list.

Ii. New ()Real parameters cannot be passed to constructors of type parameters.

3. It cannot be used at the same timeNew ()Constraints and value type constraints

 

2.5Multiple Constraints

You can use multiple constraints for the same parameter. In this case, a comma-separated constraint list is required..In this list, the first constraint must beClassOrStruct(If any) or base class (if

). SpecifyClassOrStructIt also specifies that the base class constraints are invalid. The following is interface constraints. FinallyNew ()Constraints. For example:

Class Gen <t> where T: myclass, imyinterface, new (){}

If multiple types of parameters exist,Before each type name,WhereKeywords.For example:

Class Gen <t, V> where T: Class

Where T: struct

{//.....}

2. 6. generic methods

To define generic methods,The type parameter syntax needs to be added immediately after the method name,For example

Public T method <t> (T Params)
{
Return Params;
}
You can specify constraints for generic methods.:

Public T method <t> (T Params)
Where t:Icomparable
{
Return Params;
}

2.7.defaultKeywords:

determine the type used to create a generic class instance , you need to know the most basic information : are they reference types or value types . unknown , The following Code cannot be used to grant null value :

  Public   class  mygenericclass 
   
    {T1 T1;  
    Public  
    mygenericclass () {t1  = 
    null  
    ;}}  
  

If t1 Yes Value Type , t1 it cannot be null, therefore, this code will not be compiled . fortunately , default The New Keyword usage solves this problem .
Public mygenericclass ()
{< br> T1 = default (T1);
}

The result is:IfT1Yes reference type,Give itNull,If it is a value type,Assign the default value.Such as number type,The default value is0.

Examples of several generic types:

2.8Define a generic structure

Public struct mystruct <T1, T2>
{
Public T1 Item1;
Public T2 item2;

}

2.9Define generic Interfaces
Interface myinterfacee <t> {}

2.10.Define generic methods

Public t getdefault <t> ()
{

Return default (t );

}

2.11Define generic delegation

Public Delegate T1 mydelegate <t1, T2> (t2 OP1, T2 OP2) where t1: t2

 

Conclusion: This is where the generics are. Next time we will introduce reflection. I will take some time to rewrite the first few articles about C #, so that they can be more detailed, in fact, this C # basic knowledge Review has taught me a lot of things, the vague concept of the past,

Now it is very clear. I have interviewed many people, have three years of work, have two years, and even have a longer experience than me. I know little about these basic knowledge, including myself. Because if no

With these concepts, you will not be able to consider these things in your work. Of course, you will not be able to reference them. Therefore, we can only do underlying programs. Programmers want to improve and learn these basic knowledge again. Really ......

 

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.