Generic constraints in C #

Source: Internet
Author: User

The generic constraints in C # only support the display constraints, because this ensures the type security in C #, but the display constraints are not mandatory, generic parameters can only access system. public methods in object type. "Display constraints" are expressed by the WHERE clause. You can specify "base class constraints", "interface constraints", "constructor constraints", and "value type/reference type constraints"
*****************/
Class
{
Public void F1 (){}
}
Class B
{
Public void F2 (){}
}
Class C <S, T>
Where s: A // s inherited from
Where T: B // t inherited from B
{
// You can call F1 on a variable of type S,
// You can call F2 on a variable of the T type.
}

********************/
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 use compareto on a K-type variable. You can call print and getkey on a V-type variable.
}

*********************** */
Class A {public (){}}

Class B {public B (int I ){}}

Class C <t> where T: New ()
{
// T = new T () can be used in it ();
}

C <A> C = new C <A> (); // yes; A has a constructor with or without parameters.
C <B> C = new C <B> (); // No. B does not have a constructor without parameters.

/************ Value/reference type constraints *********************/
Public struct {}

Public Class B {}

Class C where T: struct
{< br> // T here is a value type
}< br> C C = new C (); // yes. A is a value type.
C C = new C (); // No. B is a reference type.

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.