C # interface code instance,

Source: Internet
Author: User

C # interface code instance,

Class and interface implementation

Interface Definition: specify a name for a group of method signatures.

Class implementation interface, you must provide the implementation of all methods of the interface.

Even the abstract class must be fully implemented, but it can declare the interface method as abstract, and leave this interface method to the derived class for implementation, as shown below:

    public interface ITest
    {
        void Test();
    }

    public abstract class AbstractClass : ITest
    {
        public abstract void Test();
    }

    public class ConcreateClass : AbstractClass
    {
        public override void Test()
        {
            //Coding implementation;
        }
    }

14.2 define an Interface

The interface can have methods, events, and attributes, because the latter is essentially a method.

The interface cannot have static members (including constants/enumerations)

Interfaces can be "inherited" or considered as conventions that contain another interface, rather than inheritance of the true meaning.

All members under the interface. The default value is public. Do not declare

14.3 implementation Interface

The implemented interface method must be marked as public. In this case, it is virtual and sealed in IL, that is, the subclass is not allowed to override this method (new does not work at this time ).

To mark the called interface method as virtual, You can override this method in the subclass.

// If the display is marked as sealed, it cannot be rewritten.

14.4 call the Interface Method

At runtime, you can transform a variable from one interface type to another interface type, as long as the object type implements these two interfaces, as follows:

 

// String implements Icloneable and IEnumerable
String s = "Jax ";
ICloneable cloneable = s;
IEnumerable enumable = (IEnumerable) cloneable;

Note: cloneable can only use the ICloneable interface method, but cannot use the String method. Although the enumable variable is transformed from ICloneable, it cannot use the ICloneable interface method.

The value type can also be used as an interface, but it must be packed before it is converted to an interface type-the interface variable must be a reference to an object on the stack.

// Int32 implements the IFormattable Interface
Int32 I = 0;
// Pack I before converting it into an interface type
IFormattable formattable = (IFormattable) I;

14.5 implicit/display implementation of interface methods

Interface methods are generally implemented implicitly, and the accessibility must be declared as public.

EIMI: display the interface method implementation. Use the name of the interface that defines the method as the method name prefix.

It is not part of a type object. It only connects an interface to the type and avoids exposing behaviors and methods.

You cannot specify the accessibility public/private -- mark it as private in IL. You can only access this method through interface variables to prevent direct access to type objects.

It cannot be marked as virtual or overwritten.

Public interface ITest
{
Void Test ();
}

Public class TestClass: ITest
{
Public void Test ()
{
Console. WriteLine ("1 ");
}

Void ITest. Test ()
{
Console. WriteLine ("2 ");
}
} TestClass t = new TestClass ();
T. Test (); // output 1

ITest it = (ITest) t;
It. Test (); // output 2

 

14.6 generic interface

Three Benefits

1. type security during compilation

Int32 x = 1;
String s = "1 ";

IComparable c = x;
C. CompareTo (x );
C. CompareTo (s); // runtime error because the Object is of an insecure type

IComparable <Int32> cc = x; // strong type. Therefore, it is directly subject to integer x and does not accept string s. Otherwise, an error is returned during compilation.

2. Reduce packing when operating Value Type

In the previous example, the method for uploading x to Compare is to be packed. The generic type is not used for packing and is passed by value.

Non-generic types still exist in FCL for backward compatibility.

 

3. The same class can implement the same generic interface several times, as long as different types of parameters are used

     public sealed class Number : IComparable<Int32>, IComparable<String>
    {
        public int CompareTo(int other) { }

        public int CompareTo(string other) { }
    }

IComparable <Int32> and IComparable <String> can be considered as two different interfaces.

14.7 parameter constraints for generic Interfaces

Two benefits:

1. type parameters can be restricted to multiple interfaces, so that all interface constraints must be implemented for the input parameter types

2. Reduce packing

Parameter constraints generate a specific IL language so that the interface method can be called directly on the value type without packing.

14.9 use EIMI to improve the type security during compilation

Use EIMI technology to process non-generic interfaces to ensure type security

 

Struct SomeValueType: IComparable
{
Private Int32 m_x;

Public SomeValueType (Int32 x)
{
M_x = x;
}

// This is a type-safe method
Public Int32 CompareTo (SomeValueType other)
{
Return m_x-other. m_x;
}

// This is a type-insecure method, but it must be used to ensure the compilation is successful. Because of the different parameters, it can be considered as overload, and this method is the implementation of the interface method.
Int32 IComparable. CompareTo (Object other)
{
Return CompareTo (SomeValueType) other );
}
}

Note the following when calling:

SomeValueType v = new SomeValueType ();
Object o = new Object ();

Int32 n = v. CompareTo (v); // Comapre method of Class Object v to ensure type security

IComparable c = v;
N = c. CompareTo (v );
N = c. CompareTo (o); // The Comapre method of the interface Object c, which does not guarantee the type security, so do not use the interface object

14.10 disadvantages of EIMI

Three disadvantages:

1. I have not explained how to implement an EIMI method.

2. When a value type instance is converted to an interface type, it will be boxed

3. The EIMI method cannot be inherited by the derived type

14.11 interface and class inheritance

Class inheritance: indicates IS-. Easy to use, without providing all implementations; override and new rewriting; easy to add members to the base class without modifying subclass

Interface: CAN-DO. None of the above class inheritance advantages.

The value type is inherited from System. ValueType and can only be used by interfaces.

FCL collections are based on interfaces because various collections rarely share code.


A simple program of C language Bubble Sorting

Main ()
{
Int I, j, temp;
Int a [10];
For (I = 0; I <10; I ++)
Scanf ("% d,", & a [I]);
For (j = 0; j <= 9; j ++)
{For (I = 0; I <10-j; I ++)
If (a [I]> a [I + 1])
{Temp = a [I];
A [I] = a [I + 1];
A [I + 1] = temp ;}
}
For (I = 1; I <11; I ++)
Printf ("% 5d,", a [I]);
Printf ("\ n ");
}

--------------
Bubble Algorithm
Algorithm Analysis and Improvement of Bubble Sorting
The basic idea of exchanging sorting is to compare the keywords of the records to be sorted in pairs. If the order of the two records is the opposite, the two records are exchanged until there is no reverse order record.
The basic concepts of application exchange sorting include Bubble sorting and quick sorting.

Bubble Sorting

1. Sorting Method
Vertically arrange the sorted record array R [1. n]. Each record R is considered as a bubble with the weight of R. key. According to the principle that a Light Bubble cannot be under a heavy bubble, scan the array R from the bottom up: Any Light Bubble scanned to a violation of this principle will make it "float" up ". This is repeated until the last two bubbles are light and heavy.
(1) initial
R [1. n] is an unordered area.

(2) First scan
The weights of two adjacent bubbles are compared from the bottom of the unordered area to the top. If the light bubbles are found to be in the lower and severe bubbles, the positions of the two bubbles are exchanged. That is, compare (R [n], R [n-1]), (R [n-1], R [N-2]),…, (R [2], R [1]); for each pair of bubbles (R [j + 1], R [j]), if R [j + 1]. key <R [j]. key, then the contents of R [j + 1] and R [j] are exchanged.
When the first scan is complete, the "lightest" bubble floated to the top of the interval, that is, the record with the smallest keyword is placed on the highest position R [1.

(3) second scan
Scan R [2. n]. When scanning is completed, the "light" bubble floated to the R [2] position ......
Finally, the sequential area R [1. n] can be obtained through n-1 scanning.
Note:
During the I-trip scan, R [1 .. I-1] and R [I.. n] are the current sequential and disordered areas, respectively. The scan continues from the bottom of the unordered area to the top of the area. When scanning is completed, the shortest bubbles in the area float to the top position R. The result is that R [1. I] is changed to a new ordered area.

2. Bubble sorting process example
Bubble Sorting of files whose keyword sequence is 49 38 65 97 76 13 27 49

3. Sorting Algorithm
(1) Analysis
Because each sort adds a bubble to the ordered area, there are n-1 bubbles in the ordered area after N-1 sort, in the disordered area, the bubble weight is always greater than or equal to the bubble weight in the ordered area. Therefore, the entire Bubble sorting process requires at most n-1 sorting.
If no bubble position exchange is found in a sorting, it means that all bubbles in the unordered area to be sorted meet the principle of being light and heavy. Therefore, the Bubble sorting process can be terminated after this sorting. Therefore, in the following algorithm, a Boolean exchange is introduced, which is set to FALSE before each sort starts. If an exchange occurs during the sorting process, set it to TRUE. Check exchange at the end of sorting. If exchange has not occurred, terminate the algorithm and no longer perform the next sorting.

(2) specific algorithms
Void BubbleSort (SeqList R)
{// R (l. n) is the file to be sorted. It uses bottom-up scanning to perform Bubble Sorting on R.
Int I, j;
Boolean exchange; // exchange flag
For (I = 1; I <G id = "1">

A simple program of C language Bubble Sorting

Main ()
{
Int I, j, temp;
Int a [10];
For (I = 0; I <10; I ++)
Scanf ("% d,", & a [I]);
For (j = 0; j <= 9; j ++)
{For (I = 0; I <10-j; I ++)
If (a [I]> a [I + 1])
{Temp = a [I];
A [I] = a [I + 1];
A [I + 1] = temp ;}
}
For (I = 1; I <11; I ++)
Printf ("% 5d,", a [I]);
Printf ("\ n ");
}

--------------
Bubble Algorithm
Algorithm Analysis and Improvement of Bubble Sorting
The basic idea of exchanging sorting is to compare the keywords of the records to be sorted in pairs. If the order of the two records is the opposite, the two records are exchanged until there is no reverse order record.
The basic concepts of application exchange sorting include Bubble sorting and quick sorting.

Bubble Sorting

1. Sorting Method
Vertically arrange the sorted record array R [1. n]. Each record R is considered as a bubble with the weight of R. key. According to the principle that a Light Bubble cannot be under a heavy bubble, scan the array R from the bottom up: Any Light Bubble scanned to a violation of this principle will make it "float" up ". This is repeated until the last two bubbles are light and heavy.
(1) initial
R [1. n] is an unordered area.

(2) First scan
The weights of two adjacent bubbles are compared from the bottom of the unordered area to the top. If the light bubbles are found to be in the lower and severe bubbles, the positions of the two bubbles are exchanged. That is, compare (R [n], R [n-1]), (R [n-1], R [N-2]),…, (R [2], R [1]); for each pair of bubbles (R [j + 1], R [j]), if R [j + 1]. key <R [j]. key, then the contents of R [j + 1] and R [j] are exchanged.
When the first scan is complete, the "lightest" bubble floated to the top of the interval, that is, the record with the smallest keyword is placed on the highest position R [1.

(3) second scan
Scan R [2. n]. When scanning is completed, the "light" bubble floated to the R [2] position ......
Finally, the sequential area R [1. n] can be obtained through n-1 scanning.
Note:
During the I-trip scan, R [1 .. I-1] and R [I.. n] are the current sequential and disordered areas, respectively. The scan continues from the bottom of the unordered area to the top of the area. When scanning is completed, the shortest bubbles in the area float to the top position R. The result is that R [1. I] is changed to a new ordered area.

2. Bubble sorting process example
Bubble Sorting of files whose keyword sequence is 49 38 65 97 76 13 27 49

3. Sorting Algorithm
(1) Analysis
Because each sort adds a bubble to the ordered area, there are n-1 bubbles in the ordered area after N-1 sort, in the disordered area, the bubble weight is always greater than or equal to the bubble weight in the ordered area. Therefore, the entire Bubble sorting process requires at most n-1 sorting.
If no bubble position exchange is found in a sorting, it means that all bubbles in the unordered area to be sorted meet the principle of being light and heavy. Therefore, the Bubble sorting process can be terminated after this sorting. Therefore, in the following algorithm, a Boolean exchange is introduced, which is set to FALSE before each sort starts. If an exchange occurs during the sorting process, set it to TRUE. Check exchange at the end of sorting. If exchange has not occurred, terminate the algorithm and no longer perform the next sorting.

(2) specific algorithms
Void BubbleSort (SeqList R)
{// R (l. n) is the file to be sorted. It uses bottom-up scanning to perform Bubble Sorting on R.
Int I, j;
Boolean exchange; // exchange flag
For (I = 1; I <G id = "1">

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.