1. Knowledge points involved
1. Interface definition
An interface is a protocol used to define a program. It describes a set of related behaviors that can belong to any class or structure. It can be regarded as a template for implementing a set of classes. The interface can be composed of methods, properties, events and indexers or any combination of these 4 member types, but cannot contain fields. Classes and structures can be inherited from interfaces just like a class inherits a base class, but can inherit multiple interfaces. When a class or structure inherits an interface, it inherits member definitions but not implementations. To implement an interface member, the corresponding member in a class or structure must be public, non-static, and have the same name and signature as the interface member. The properties and indexers of a class or structure can define additional accessors for properties or indexers defined in the interface. For example, an interface may declare a property with a get accessor, and a class implementing the interface may declare the same property with both get and set accessors. However, if the property or indexer is implemented explicitly, the accessor must match.
In addition, an interface can also inherit other interfaces. A class can inherit an interface multiple times through the base class or interface it inherits. In this case, if the interface is declared as part of a new class, the class can only implement the interface once. If the inherited interface is not declared as part of the new class, its implementation will be provided by the base class that declares it. The base class can implement interface members using virtual members. In this case, classes that inherit the interface can change the interface behavior by overriding the virtual members.
In C#, the interface keyword is used to declare the interface, and the syntax format is as follows:
Modifier interface interface name: inherited interface list
{
//Interface content;
}
illustrate:
When declaring an interface, it usually starts with the capital letter "I".
When declaring an interface, except for the interface keyword and interface name, all other options are available.
The interface can be declared using modifiers such as new, public, protected, internal and private, but the interface members must be public.
2. Features of the interface
Interfaces are similar to abstract base classes, and any non-abstract type inheriting an interface must implement all members of the interface.
The interface cannot be instantiated directly.
An interface can contain events, indexers, methods, and properties. The interface does not contain the implementation of the method.
Classes and structures can be inherited from multiple interfaces.
The interface itself can be inherited from multiple interfaces.
3. Interfaces are implemented through class inheritance
Although a class can only inherit one base class, it can inherit as many interfaces as possible. When declaring a class that implements an interface, you need to include the name of the interface implemented by the class in the base class list.
The syntax format for inheritance in C# is as follows:
class DerivedClass:BaseClass {}
illustrate:
When inheriting an interface, you must use a colon (:) between the subclass and the interface.
In addition, if multiple interfaces are inherited, then each interface inherited is separated by a comma (,).
4. Effectively use interfaces for component programming
Interface separates the service's protocol from implementation. It is the basis of component programming. In component programming, interfaces are the only way for components to publish their functions to the outside.
(String) method
The (String) method in C# is used to convert the specified string into a byte array. This method belongs to the class, which provides static methods for converting characters to bytes and converting bytes to characters.
public static byte[] GetBytes(string str);
parameter
str String A string containing the characters to be encoded.
return
Byte[] An byte array containing the results of encoding the specified character set.
In this example, this method is used to encode the string into a UnicodeEncoding sequence.
(1) Check whether the given string contains Chinese characters
In a loop, each iteration checks whether the next byte of the current byte (byte at index i+1) is not equal to 0. Because in Unicode encoding, a Chinese character is usually represented by two bytes, if the next byte is not equal to 0, it means that the current byte represents part of a Chinese character.
If Chinese characters are found, set flag to true. Otherwise, keep flag as false.
After the loop is finished, the value of flag is returned to indicate whether the Chinese characters are found in the string.
/// <summary> /// Check whether the given string contains Chinese characters/// </summary> public static bool IsChineseChecked(string str) { bool flag = false; UnicodeEncoding a = new(); byte[] bt = (str);// When overriding in a derived class, encode all characters in the specified character array into a sequence of bytes. for (int i = 0; i < ; i++) { i++; if (bt[i] != 0) { flag = true; } else { flag = false; } } return flag; }
(2) Before and after encoding and restoration
The encoding result is to obtain a sequence of byte arrays of numeric expressions.
The result of restoration is to restore the encoding to the source string.
// Encoding as a byte array using the Encoding.(String) method// Restore to a string using the Encoding.(byte[]) methodusing ; namespace _117_1 { class Program { static void Main(string[] args) { (args); string str = "Hello, World!"; byte[] bytes = Encoding.(str); ("Original string: " + str); ("Byte array length: " + ); ("Byte array: " + (", ", bytes)); // Convert back to string string backToString = Encoding.(bytes); ("Back to string: " + backToString); ("********************************"); string str1 = "Great Wall"; byte[] bytes1 = Encoding.(str1); ("Source String:" + str1); ("Byte array length: " + ); ("Byte array: " + (", ", bytes1)); // Convert back to string string backToString1 = Encoding.(bytes1); ("Restore to source string:" + backToString1); } } } //Run result:/* Original string: Hello, World! Byte array length: 13 Byte array: 72, 101, 108, 108, 111, 44, 32, 87, 111, 114, 108, 100, 33 Back to string: Hello, World! *************************************** Source string: Great Wall Byte array length: 12 Byte array: 228, 184, 135, 233, 135, 140, 233, 149, 191, 229, 159, 142 Restore to source string: Great Wall */
(Byte[]) method
The (byte[]) method in C# is used to decode a byte array into a string. It belongs to a class that provides static methods and properties for converting characters to bytes and converting bytes to characters.
public virtual string GetString (byte[] bytes);
parameter
bytes Byte[] An array of bytes containing the sequence of bytes to be decoded.
return
String contains the string that specifies the decode result of the byte sequence.
(1) Example
// Use the (byte[]) methodusing ; namespace _117_2 { internal class Program { private static void Main(string[] args) { (args); // Create a Unicode encoding instance Encoding unicodeEncoding = Encoding.UTF8; // Define a byte array containing some byte representations of Unicode characters byte[] bytes = [0x04, 0x41, 0x04, 0x42, 0x04, 0x43]; // Use Unicode encoding to decode the byte array into a string string decodedString = (bytes); // Output the decoded string (decodedString); } } } //Run result:/* ABC */
2. Examples
An interface can be established in a program that defines a method for dialogue, and the dialogue method is implemented in a class. Create a Chinese class and an American class respectively. Both classes inherit from interfaces. They speak Chinese in Chinese classes and English in American classes. When communicating with people from different countries, instantiate the interface and call the methods in the corresponding class.
1. Source code
// using ; namespace _117 { public partial class Form1 : Form { private Label? label1; private Button? button1; private ComboBox? comboBox1; private TextBox? textBox1; public Form1() { InitializeComponent(); StartPosition = ; Load += Form1_Load; } private void Form1_Load(object? sender, EventArgs e) { // // label1 // label1 = new Label { AutoSize = true, Location = new Point(12, 18), Name = "label1", Size = new Size(80, 17), TabIndex = 0, Text = "Select a conversation person:" }; // // button1 // button1 = new Button { Location = new Point(226, 12), Name = "button1", Size = new Size(75, 23), TabIndex = 2, Text = "dialogue", UseVisualStyleBackColor = true }; += Button1_Click; // // comboBox1 // comboBox1 = new ComboBox { FormattingEnabled = true, Location = new Point(98, 12), Name = "comboBox1", Size = new Size(121, 25), TabIndex = 3, //SelectedIndex = 0 }; ([ "xxx", "yyy"]); // // textBox1 // textBox1 = new TextBox { Location = new Point(12, 43), Multiline = true, Name = "textBox1", Size = new Size(290, 161), TabIndex = 4 }; // // Form1 // AutoScaleDimensions = new SizeF(7F, 17F); AutoScaleMode = ; ClientSize = new Size(314, 216); (textBox1); (comboBox1); (button1); (label1); Name = "Form1"; Text = "Use interface to realize conversation in different languages"; } /// <summary> /// Button event /// Select the language of the call object and enter the call content of the language /// </summary> private void Button1_Click(object? sender, EventArgs e) { if (textBox1!.Text == "") { ("Don't you want to say something?", "warn", , ); return; } else { if (comboBox1!.SelectedIndex == 0)//Conversation with xxx people { if (IsChineseChecked()) { ISelectLanguage Interface1 = new C_SpeakChinese(); (); } else { ("Say xx to xxx", "warn", , ); return; } } else//Conversation with yyy { if (IsChineseChecked()) { ("Say yyy with yy!", "warn", , ); return; } else { ISelectLanguage Interface1 = new C_SpeakEnglish(); (); } } } } /// <summary> /// Declare an interface to define Seak methods, and the implementation of the specific Speak method functions is carried out in the class /// </summary> interface ISelectLanguage { void Speak(string str); } /// <summary> /// If you talk to xxx, say xx /// </summary> class C_SpeakChinese : ISelectLanguage { public void Speak(string str) { ("Say to xxx:" + str, "hint", , ); } } /// <summary> /// If you talk to yy, say yy /// </summary> class C_SpeakEnglish : ISelectLanguage { public void Speak(string str) { ("Say to yyy: + str, "hint", , ); } } public static bool IsChineseChecked(string str) { bool flag = false; UnicodeEncoding a = new(); byte[] bt = (str);// When overriding in a derived class, encode all characters in the specified character array into a sequence of bytes. for (int i = 0; i < ; i++) { i++; if (bt[i] != 0) { flag = true; } else { flag = false; } } return flag; } } }
The above is the detailed content of C# using interfaces to implement multilingual selection functions. For more information about C# multilingual selection, please pay attention to my other related articles!