C # generic Programming __ Programming

Source: Internet
Author: User
Tags int size

Feeling for the work of programming, I started to think so, or we are now good. For example, the language developed, developed into easier to understand and programming, tools also developed, programming time is more convenient, such as the current smart tips.

But it seems a bit one-sided, and it's hard to really understand the history of a technology without understanding it. C # Generic programming is 2.0, but its own understanding is not enough, hereby summed up. C # generics and mechanisms

C # Generic Demo

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

Namespace ConsoleApplication1
{
    class program
    {
        static void Main (string[] args)
        {
            stack< int> test = new stack<int> ();
            Test. Push (ten);
            Console.WriteLine (Test. GetResult ());
            Console.read ();
        }

    Class stack<t> 
    {
        private t[] store;
        private int size;

        Public Stack ()
        {
            store = new T[10];
            size = 0;
        }

        public void Push (T x)
        {
            store[size++] = x;
        }

        Public T POPs ()
        {return
            store[--size];
        }

        public string GetResult ()
        {return
            store[--size]. ToString ();}}}


Introduction of C # generics

The so-called generics, that is, through parameterized types to implement the operation on the same code a variety of data types. Generic programming is a programming paradigm that uses "parameterized types" to abstract types to achieve more flexible reuse.

C # generics give code stronger type safety, better reuse, higher efficiency, clearer constraints

Introduction to C # generics mechanism

C # Generic capabilities are supported by the CLR at runtime, different from the compile-time template mechanism of C + +, and Java's compile-time "wiping" method. This allows generics to interoperate seamlessly between the various languages that support the CLR.

C # generic code, when compiled into IL code and metadata, uses special placeholders to represent generic types and supports generic operations with proprietary IL directives. The true generics instantiation works in a "on-demand" manner, which occurs at JIT-compilation time.

C # Generic compilation mechanism

At the first round of compilation, the compiler produces only the IL Code and metadata for the stack<t> type "generic version"--it does not instantiate the generic type, and T only acts as a placeholder in the middle

At JIT compilation time, when the JIT compiler encounters stack<int> for the first time, an int replaces the generic version IL code with the t--in the metadata to instantiate the generic type.

The CLR produces the same code for a generic type with all type parameters of reference type, but if the type argument is a value type, the CLR generates a separate code for each of the different value types

Several features of C # generics

If the parameters of the instantiated generic type are the same, the JIT compiler uses the type repeatedly, so the dynamic generics capability of C # avoids the problem of code bloat that can be caused by a C + + static template.
C# generic types carry rich metadata, so C # 's generic types can be applied to powerful reflection techniques.
C# 's generics take the "base class, interface, constructor, value type/reference type to implement the" explicit constraint "on the type parameter, which improves the type safety and loses the high flexibility of C + + template based on the implicit constraint of" signature ". generic type

C # generic classes and structs

Class C<u, v> {}   //Legal
    class d:c<string, int> {}    //Legal
    class E<u, v>: C<u, v> { }     //Legal
    class F<u, v>: C<string, int> {}  //Legal
    //illegal
    //class g:c<u, v> {};


In addition to declaring generic types (including classes and structs) separately, C # can also include declarations of generic types in the base class. However, if the base class is a generic class, its type parameter is either instantiated or derived from a type parameter declared by a subclass (also a generic type).

Members of a generic type

Class d<v>
    {
        
    }

    class c<v>
    {public
        V fi1;   Declare field public
        d<v> F2;  Parameter public
        C (V x)   
        {
            this.fi1 = x;
        }
    } for other generic types


Members of a generic type can use type parameters in a generic type declaration. However, if there are no constraints on the type parameter, only public members inherited from System.Object can be used on that type.

Generic interface

Interface ilist<t>
    {
        t[] getelements ();
    }
    Interface Idictionary<k, v>
    {=
        void Add (K key, V value);
    }

    Class List<t>: ilist<t>,idictionary<int,t>
    {public

        void Add (int key, T value)
        {
            throw new NotImplementedException ();
        }

        Public t[] GetElements ()
        {
            throw new notimplementedexception ();
        }
    }


The type parameters of a generic interface are either instantiated or derived from the type arguments of the implementation class declaration.

Generic delegate

delegate bool Predicate<t> (T value);
    Class X
    {
        static bool F (int i) {return true;}
        static bool G (string s) {return false;}

        static void Main ()
        {
            predicate<string> P2 = G;
            predicate<int> P1 = new predicate<int> (F);
        }
    }


Generic delegates support the application of parameter types on delegate return values and parameters, which can also be accompanied by legitimate constraints. generic Method

Introduction to Generic methods

The C# generic mechanism only supports "including type parameters on method declarations"--that is, generic methods
The C# generic mechanism does not support the inclusion of type parameters on declarations of other members except methods, including properties, events, indexers, constructors, destructors, but those members themselves can be contained in generic types and use the type parameters of generic types
• A generic method can be contained either in a generic type or in a non-generic type

Declaration and invocation of generic methods

public class Finder
    {
        //generic method declaration public
        Static int find<t> (t[] items, T item) {for
            (int i = 0; i < items. Length; i++)
            {
                if (items[i]. Equals (item))
                {return
                    i;
                }
            }
            return-1;
        }

        Invocation of generic method
        int i = finder.find<int> (new int[] {1,3,4,5,6}, 6);
    }


Overloads of generic methods

public class MyClass
    {
        void f1<t> (t[] a,int i);
        void F1<u> (u[] A, int i);   Can not constitute an overloaded method

        void f2<t> (int x);
        void F2 (int x);     Can form an overloaded method

        void f3<t> (T-t) where t:a;
        void f3<t> (T-t) where t:b;
    }

    Class a{}
    class B {}


Override of a generic method

Abstract class Base
    {public
        abstract T f<t, u> (T T, u u) where u:t;
        Public abstract T G<t> (T-t) where t:icomparable;
    }

    Class Derived:base
    {
        //legal override, constraint is inherited by default public
        override T f<t, u> (T, u u)
        {
            throw new notimple Mentedexception ();
        }

        Illegal overrides, specifying that any constraint is redundant public
        override T g<t> (t) where t:icomparable
        {
            throw new NotImplementedException ();
        }
    
generic constraint

Overview of generic constraints

The C# generic requires that any assumption of the type parameters of all generic types or generic methods be based on explicit constraints to maintain type safety as required by C #.
• "Explicit constraints" are expressed by a WHERE clause, which allows you to specify a "base class constraint", "Interface Constraint", "constructor constraint", and "value type/reference type constraint" altogether four constraints.
• "Explicit constraint" is not necessary, and if "explicit constraint" is not specified, the generic type parameter will only be able to access the public method in the System.Object type.

Base class constraints

Class a{public void F1 () {}}
    class B {public void F2 () {}}
    class c<s,t>
        where S:a   //s inherits from A
        wher E t:b   //t inherits from B
    {
        //can be invoked on a variable of type S
        //Can be invoked on a variable of type T (F2
        
    }


interface constraints

Interface Constraint 
    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>
    {
        //  can invoke CompareTo on a variable of type K//
        /  can call print and Getkey} on a variable of type V
    


Constructor constraint

Class A{public A () {}}
    class B{public B (int i) {}}

    class w<t> where T:new ()
    {
        
    } public
   class Test
   {
       w<a> c=new w<a> ();   Can have a parameterless constructor
       w<b> c=new w<b> ();   Error, b no parameterless constructor
   }


Value type/reference type constraint


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.