Was ist eine Schnittstelle?
Die Schnittstelle repräsentiert einsFähigkeitUnd die abstrakte Klasse ist höher als die Abstraktionsklasse!
Definition der Schnittstelle:
1 öffentlich SchnittstelleEssen// Definiere eine Schnittstelle2{3 LeereEssen(ZeichenfolgeEssen);// Definieren Sie eine Funktion für die Schnittstelle4}Schnittstellendefinition
Aus dem Beispiel oben können wir ersehen, dass die Methode in der Schnittstelle istEs gibt keine Möglichkeit, ohne die Methode auf den Modifikator zuzugreifen.Haben. Und es kann nur Methoden, Attribute, Indexer und Ereignisse in der Schnittstelle geben!
Die Nutzung der Schnittstelle:
1
Öffentliche Klasse
Hund: Fressen// DOG-Klasse implementiert die IEAT-Schnittstelle2{3 // Die DOG-Klasse implementiert die EAT-Methode für die IEAT-Schnittstelle4 öffentlich LeereEssen(ZeichenfolgeEssen)5{6Console.WriteLine("essen„+Essen);7}8}
Schnittstellennutzung
Hinweis: Wenn eine Klasse eine Schnittstelle implementiert, muss diese Klasse die von der Schnittstelle und ihrer übergeordneten Schnittstelle verwendete Methode implementieren, es sei denn, die Klasse ist eine Unterklasse der Klasse, sie wird implementiert! Eine Schnittstelle kann auch eine andere Schnittstelle erben, ohne die Schnittstelle zu implementieren, um sie zu implementieren
Demo:
1 // Schnittstelle eins2 öffentlichSchnittstelle IEat3{4 LeereEssen();5}6 // Schnittstelle 27 öffentlichIpaly-Schnittstelle8{9 LeereSpielen();10}11 // Schnittstelle drei12 öffentlichSchnittstelle Itravel:IEat,Ipaly13{14 // Schnittstelle drei vererbt Schnittstelle eins und Schnittstelle zwei15}16 17 öffentlich KlasseProgramm:Itravel18{19 öffentlich LeereEssen()20{21 // Den Methodenkörper weglassen22}23 öffentlich LeereSpielen()24{25 // Den Methodenkörper weglassen26}27}Modus
Einige der IEAT-Schnittstellen und iPaly-Schnittstellen, die in der obigen Demo zu sehen sind, stellen möglicherweise einige Freunde vor die Frage: „Unterstützen Sie nicht mehr Vererbung in C # und Java?“
Beachten Sie, dass dies auf eine Klasse abzielt, aber für eine Schnittstelle bedeutet eine Klasse, dass dieselbe Schnittstelle, die mehrere Schnittstellen implementieren kann, auch mehrere Schnittstellen erben kann.
Unterschiede zwischen Schnittstellen und abstrakten Klassen:
Wenn zwischen den verschiedenen benötigten Objekten eine übergeordnete Klassenbeziehung besteht, können Sie die Verwendung einer abstrakten Klasse in Betracht ziehen.
Wenn zwischen den einzelnen Objekten keine Vererbungsbeziehung besteht, werden nur die gleichen Funktionen und die Schnittstelle berücksichtigt
Abstrakte Klassen sind ein abstraktes Ergebnis einer bestimmten Art von Dingen und die Schnittstelle repräsentiert bestimmte Dinge.
Übernahme der Schnittstelle:
01. Die Schnittstelle ist für das Format der Einschränkungsmethode (Parameter und Rückgabewerttyp) vorhanden.
02. Die Schnittstelle kann mehr Vererbung erreichen und die Mängel der einzelnen Vererbung ausgleichen.
03. Die Schnittstelle kann als spezielle Abstraktionsklasse betrachtet werden, und Sie können den Quellcode durch Antikompilierung anzeigen.
04. Die Methode in der Schnittstelle muss nicht auf den Modifikator zugreifen, da die CLR automatisch hinzugefügt wird und es keinen Methodenkörper gibt.
05. Wenn eine Klasse eine Schnittstelle implementiert, müssen Sie alle Methoden in der Schnittstelle implementieren.
06. Die Schnittstelle sollte mit Vorsicht verwendet werden, um eine Verschmutzung der Schnittstelle zu vermeiden!
07. Die Schnittstelle stellt nur eine Fähigkeit dar und erbt nicht die Beziehung zwischen der Klasse und der Schnittstelle der Schnittstelle.
08. Die Schnittstelle wird zum Implementieren verwendet, die Klasse wird zum Erben verwendet.
09. Tatsächlich scheint es oft keine Schnittstelle zu geben, weil die Schnittstelle eine Möglichkeit ist, zuzustimmen,
10. Abstrakte Klassen können auch Schnittstellen implementieren, Schnittstellenmitglieder müssen jedoch abstrakte Mitglieder abstrakter Klassen zuordnen. Wenn die abstrakte Klasse eine abgeleitete Klasse ist und es sich um eine nicht abstrakte Klasse handelt, muss sie von der Methode abgerufen werden.
Warum einen Indexer verwenden?
Analyse: Die Verwendung eines Indexers, wenn eine Klasse ein Array oder ein Sammlungsmitglied enthält, kann den Zugriffsvorgang auf das Array oder ein Sammlungsmitglied erheblich vereinfachen.
Definition des Indexers
Die Definition und das Attribut des Indexers sind ähnlich
1 / * [Modifikator] Datentyp THIS [Indextyp INDEX]2{3Holen Sie sich {// Holen Sie sich den Code der Eigenschaft}4Festlegen {// Legen Sie den Code der Eigenschaft fest}5}6*/Definitionssyntax des Indexers
Demo:
1 2 öffentlich KlasseStudenten3{4 Zeichenfolge[] Namen =neu Zeichenfolge[3];5 öffentlich Zeichenfolge Das[intIndex] {6 erhalten{zurückkehrenNamen[Index];}7 Satz{Namen[Index]=Wert;}8}9 int[] Alter =neu int[3];10 öffentlich int Das[ZeichenfolgeTaste]11{12 13 erhalten{14 für(intich = 0; i < Namen.Länge;i++ )15{16 Wenn(Key.Equals(names[i]))17{18 zurückkehrenAlter[i];19}20}21 zurückkehren-1;22 23}24 Satz25{26 für(intich = 0; i < Namen.Länge; i++)27{28 Wenn(Key.Equals(names[i]))29{30Alter[i]=Wert;31}32}33;34}35}36}
Demo
Warum kann ich Foreach-Traversen verwenden?
Analyse: Da Arrays und Sammlungen die IENUMERABLE-Schnittstelle aktivieren, kann Foreach nur eine Methode getenumerator () verwenden, solange die ienumerable-Schnittstelle durchlaufen werden kann.
1 // Zusammenfassung:2 // Öffentliche Aufzählungsnummer, die Nummer unterstützt die einfache Iteration in einer nicht schwebenden Sammlung.3[ComVisible(WAHR)]4[Anleitung("496B0ABE-CDEE-11d3-88E8-00902754C43A")]5 öffentlich SchnittstelleIEnumerable6{7 // Zusammenfassung:8 // Gibt eine rezirkulierende Zugriffssammlung zurück.9 //10 // Das Ergebnis zurückgeben:11 // Ein system.collections.ienumerator-Objekt, das für den Schleifenzugriff verwendet werden kann.12[DispId(-4)]13IEnumerator GetEnumerator();14}Unzähliger Prototyp
Aus dem obigen Code können wir ersehen, dass die genumerator()-Methode der IEnumerable-Schnittstelle ein Objekt zurückgibt, das die IENUMERATOR-Schnittstelle implementiert!
1 // Zusammenfassung:2 // Unterstützung für einfache Iterationen für nicht blühende Sammlungen.3[ComVisible(WAHR)]4[Anleitung("496B0ABF-CDEE-11d3-88E8-00902754C43A")]5 öffentlich SchnittstelleIEnumerator6{7 // Zusammenfassung:8 // Holen Sie sich das aktuelle Element in der Sammlung.9 //10 // Das Ergebnis zurückgeben:11 // Das aktuelle Element in der Sammlung.12 ObjektAktuell {erhalten; }13 14 // Zusammenfassung:15 // die aufgezählte Zahl zum nächsten Element der Sammlung vorrücken.16 //17 // Das Ergebnis zurückgeben:18 // Wenn die Anzahl der Aufzählungen erfolgreich zum nächsten Element übergeht; Wenn die Anzahl der Aufzählungen das Ende der Auflistung überschreitet, ist „false“ „false“.19 //20 // Abnormal:21 // System.InvalidOperationException:22 // Die Sammlung wird geändert, nachdem die Anzahl der Aufzählungen erstellt wurde.23 boolMoveNext();24 //25 // Zusammenfassung:26 // Setze die Aufzählungszahl auf ihre Anfangsposition, die vor dem ersten Element in der Sammlung liegt.27 //28 // Abnormal:29 // System.InvalidOperationException:30 // Die Sammlung wird geändert, nachdem die Anzahl der Aufzählungen erstellt wurde.31 LeereZurücksetzen();32}Ienumerator-Prototyp
Wenn wir foreach verwenden, um ein Objekt zu übergeben, führen Sie die teamförmige GetieNumerable-Methode aus, um einen Iterator (Objekt der IEnumerator-Schnittstelle) abzurufen, rufen dann die RESET-Methode für das Objekt auf, um es zunächst aufzuzählen, und führen dann die MoveNext (Methode Get) des Objekts aus Der BOOL-Wert. Wenn die Methode „true“ zurückgibt, erhält die CURRENT-Eigenschaft, die das Objekt aufruft, den Wert. Es führt die MOVENEXT()-Methode aus, bis die Methode eine Hypothese zum Beenden der Iteration zurückgibt.
Demo:
1 // Eine Klasse, die in Foreach durchlaufen werden kann (IENMERABLE-Schnittstelle)2 öffentlich KlasseMyList:IEnumerable3{4ArrayList-Liste =neuAnordnungsliste();5 öffentlich LeereHinzufügen(ObjektÖ)6{7list.Add(o);8}9 öffentlichIEnumerator GetEnumerator()10{11 zurückkehren neuMyIenumerator(list);12}13}14 // Realisiere die Klasse der Ienumerator-Schnittstelle15 öffentlich KlasseMyIenumerator:IEnumerator16{17 öffentlichMyIenumerator(ArrayList-Liste)18{19 Das.list = Liste;20}21ArrayList-Liste =neuAnordnungsliste();22 intI = -1;23 öffentlich ObjektAktuell24{25 erhalten{zurückkehrenlist[I]; }26}27 28 öffentlich boolMoveNext()29{30 boolfallen =FALSCH;31 Wenn(I32{33I++;34fallen =WAHR;35}36 zurückkehrenfallen;37}38 39 öffentlich LeereZurücksetzen()40{41 42}43} Angepasste Klasse für Foreach-Traversal
FAQs
How do you find the index of a foreach loop? ›
- using System;
- using System. Collections. Generic;
- public class IndexOfIteration.
- {
- public static void Main()
- {
- var numbers = new List<int>() { 1, 2, 3, 4, 8, 10 };
- int index = 0;
- Option 1: Create and manage an integer loop variable yourself.
- Option 2: Use a tuple to get the foreach loop's value and index.
- Option 3: Replace foreach with the for statement.
Get The Current Array Index in JavaScript forEach()
JavaScript's forEach() function takes a callback as a parameter, and calls that callback for each element of the array: // Prints "a, b, c" ['a', 'b', 'c']. forEach(function callback(v) { console. log(v); });
How to find the index of an item in a C# list in a single step? To get the index of an item in a single line, use the FindIndex() and Contains() method. int index = myList. FindIndex(a => a.
How to get index of repeated elements in array Java? ›- public class DuplicateElement {
- public static void main(String[] args) {
- //Initialize array.
- int [] arr = new int [] {1, 2, 3, 4, 2, 7, 8, 8, 3};
- System.out.println("Duplicate elements in given array: ");
- //Searches for duplicate element.
- for(int i = 0; i < arr.length; i++) {
- for(int j = i + 1; j < arr.length; j++) {
Java String indexOf() Method
The indexOf() method returns the position of the first occurrence of specified character(s) in a string. Tip: Use the lastIndexOf method to return the position of the last occurrence of specified character(s) in a string.
The IndexOf() method of array class in C# searches for the specified object and returns the index of the first occurrence within the entire one-dimensional Array.
How to check if a string array index exists in C#? ›Use the Equals method to check if an item exists in a C# array. string subStr = "pqrs"; string[] str = { "abcd", "ijkl", "pqrs", "wxyz" }; Now check whether the substring is part of the string or not using the Equals method.
How to get index from string array in C#? ›Use the FindIndex() Method From the Array Class to Find a Partial Match. This method returns the index of the first string that contains the value du .
How to add each index in an array JavaScript? ›If you need to add an element to the beginning of your array, use unshift() . If you want to add an element to a particular location of your array, use splice() . And finally, when you want to maintain your original array, you can use the concat() method.
How to get particular index from array in JavaScript? ›
The indexOf() method returns the first index (position) of a specified value. The indexOf() method returns -1 if the value is not found. The indexOf() method starts at a specified index and searches from left to right. By default the search starts at the first element and ends at the last.
How to find the index of each element in an array JavaScript? ›To find the position of an element in an array, you use the indexOf() method. This method returns the index of the first occurrence the element that you want to find, or -1 if the element is not found.
How to check if list index is out of range in C#? ›Another way of checking if an array is out of bounds is to make a function. This will check if the index is "in bounds". If the index is below zero or over the array length you will get the result false. This should be built in as a member function of the array class..
How to remove index element from list in C#? ›To remove an item from a list in C# using index, use the RemoveAt() method.
How to check last index in C#? ›LastIndexOf() Method in C# The Array. LastIndexOf() method in C# is used to search for the specified object and returns the index of the last occurrence within the entire one-dimensional Array.
How to find index of duplicate elements in list javaScript? ›- Using the indexOf() method.
- Using the has() method.
- Using an object & key value pairs.
- Using the "some" function.
- Using iteration.
The findIndex() method executes a function for each array element. The findIndex() method returns the index (position) of the first element that passes a test. The findIndex() method returns -1 if no match is found. The findIndex() method does not execute the function for empty array elements.
How to increment each element in array Java? ›- import java.util.Scanner;
- public class Increment_Array.
- {
- public static void main(String[] args)
- {
- int n, i = 0;
- Scanner s = new Scanner(System. in);
- System. out. print("Enter no. of elements you want in array:");
Answer. To know if one text string is contained in another text string use the Text Built-in Function Index. The Index Function returns an integer with the zero-base position of a keyword string inside another text string and returns -1 if keyword is not found.
How to get substring index from string in Java? ›Java String substring() Methods
substring(int beginIndex, int endIndex) : The substring begins at the specified beginIndex and extends to the character at index endIndex - 1. Thus the length of the substring is (endIndex - beginIndex).
How to get specific string from string in Java? ›
- Public String substring(int startIndex) This method gives a new String object that includes the given string's substring from a specified inclusive startIndex. ...
- Public String substring(int startIndex, int endIndex):
The indexof() method in Javascript is one of the most convenient ways to find out whether a value exists in an array or not. The indexof() method works on the phenomenon of index numbers. This method returns the index of the array if found and returns -1 otherwise.
Is it possible to find the index of an element in an array? ›The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.
How to check array index value is empty in Java? ›A java empty array can be declared using the new keyword. To check whether an array is empty or not in Java, we can check if its length is0 or if all the elements in the array are null values.
How do you check if a string is already in an array? ›You can use the includes() method in JavaScript to check if an item exists in an array. You can also use it to check if a substring exists within a string. It returns true if the item is found in the array/string and false if the item doesn't exist.
How do I check if a string is in an array list? ›ArrayList. contains() method can be used to check if an element exists in an ArrayList or not. This method has a single parameter i.e. the element whose presence in the ArrayList is tested. Also it returns true if the element is present in the ArrayList and false if the element is not present.
How to check if a list contains empty string in C#? ›Now to check whether a list is empty or not, use the Count property. if (subjects. Count == 0) Console.
How do I get a specific index from a string? ›You can get the character at a particular index within a string, string buffer, or string builder by invoking the charAt accessor method. The index of the first character is 0; the index of the last is length()-1 .
How to convert array index to string in Java? ›- Using String class Constructor.
- Using valueOf() Method.
- Using copyValueOf() Method.
- Using StringBuilder Class.
In C#, the Insert() method takes a string and inserts it into another string. Insert() accepts the index position to start the insertion from, inserts the second string at the index position of the first string, and then returns the modified string.
How do you access items in an array in JavaScript? ›
An item in a JavaScript array is accessed by referring to the index number of the item in square brackets. We know 0 will always output the first item in an array. We can also find the last item in an array by performing an operation on the length property and applying that as the new index number.
How to add two array indexes in Java? ›- Step 1 − Declare and initialize an integer array.
- Step 2 − Check if the length of both arrays is equal or not.
- Step 3 − If the length of both arrays is equal then add them using “a1[] + a2[] = a3[]”.
- Step 4 − Print the resultant array.
- Step 5 − Otherwise print "Length of both arrays should be same".
- Initialize sum = 0 .
- Run a for loop from i = 0 to i = size - 1 .
- At every iteration of the for loop, add sum and the current element of the array, i.e., sum = sum + arr[i] .
- At the end of the for loop, the sum of all the elements will be stored in the sum variable.
In JavaScript, you can simply do: const first = arr[0];
How to find element in array by index in typescript? ›Using The indexOf() Method to Search For an Element in The Array. The indexOf() method takes an array element as a parameter rather than taking a callback function. It returns the index of the first occurrence of the element in the array.
How to get the index of a set in JavaScript? ›To get an index of an element in JavaScript, you can use the “indexOf()” function. The array indexOf() is a built-in method that returns the first index at which a given element can be found in the array, or -1 if it is not present.
How to avoid index out of range exception in C#? ›To correct this error, check the search method's return value before iterating the array, as shown in this example. using System; using System. Collections. Generic; public class Example { static List<int> numbers = new List<int>(); public static void Main() { int startValue; string[] args = Environment.
How to check if an index is out of range in Java? ›In order to check whether or not an index is in range [0, n) we can rely on a “if” statement, as below: if (index = n) { ... } But, Java 9 comes with the method bjects. checkIndex() that checks if the given index is in range [0, n).
How to check if data exists in a list C#? ›Syntax. public bool Contains (T value); It takes the T value as input, to be searched in the linked list. It returns true if the value is present in the linked list and false otherwise.
How to remove the element from an index in Java list? ›- E remove(int index ) : This method removes the element at the specified index and returns it. The subsequent elements are shifted to the left by one place. ...
- boolean remove(Object o ) This method removes the first occurrence of the specified Object .
How do I remove an element from a list using index value? ›
You can use the pop() method to remove specific elements of a list. pop() method takes the index value as a parameter and removes the element at the specified index. Therefore, a[2] contains 3 and pop() removes and returns the same as output. You can also use negative index values.
How do I remove a specific element index from an array? ›You can remove the element at any index by using the splice method. If you have an array named arr it can be used in this way to remove an element at any index: arr.splice(n, 1) , with n being the index of the element to remove. The splice method can accept many arguments.
How to get a substring from index to end in C#? ›You can use the Substring() method to get a substring in C#. The Substring() method takes the index position to start the retrieval of the substring as a parameter. Substring() can also take an optional parameter, which is the length of strings to return.
How to check last index of string in Java? ›Java String lastIndexOf() Method
The lastIndexOf() method returns the position of the last occurrence of specified character(s) in a string. Tip: Use the indexOf method to return the position of the first occurrence of specified character(s) in a string.
The Length property, Count() extension method of LINQ or the IsNullOrEmpty() method can be used to check if the array is empty. If any of these methods return 0 or the array is null, it can be determined that the array is empty.
Can we obtain the array index using foreach loop? ›Can we obtain the array index using foreach loop in C#? Explanation: No, we cannot obtain the array index using foreach loop because it does not keep track of the index, it only iterates forward over the array in single steps.
What is the index of a loop? ›An index loop repeats for a number of times that is determined by a numeric value. An index loop is also known as a FOR loop.
Can you get the index in a for each loop Java? ›The for-each loop simplifies the code by hiding the complexity behind the iterator() method. There is no direct provision to access the index of the current element with for-each construct, since it is used to loop over an Iterable, and not all Iterables actually have an index.
How to get index in for each loop in Swift? ›- Use indices property.
- Use enumerated() method.
- Use zip method with indices property.
Use the return keyword
The return keyword stops the execution of the code. In the forEach() loop, it works as a continue statement.
How do you check if there are repeats in an array? ›
Using the indexOf() method
In this method, what we do is that we compare the index of all the items of an array with the index of the first time that number occurs. If they don't match, that implies that the element is a duplicate.
You can loop through the array elements with the for loop, and use the length property to specify how many times the loop should run.
What is index [- 1 of an array in Python? ›Negative numbers mean that you count from the right instead of the left. So, list[-1] refers to the last element, list[-2] is the second-last, and so on.
How do you access the index of an array in Python? ›We can access elements of an array using the index operator [] . All you need do in order to access a particular element is to call the array you created. Beside the array is the index [] operator, which will have the value of the particular element's index position from a given array.
What does [- 1 index mean in R? ›[,-1] selects all columns except column 1. Note that, unlike in C++, indices in R start from one rather than zero.
How to get string between two indexes in Java? ›- Find index of first character in String.
- Find index of second character in the String.
- Use String's substring() method to get String between these two indices.
The String class provides an indexOf() method that returns the index of the first appearance of a character in a string. To get the indices of all occurrences of a character in a String, you can repeatedly call the indexOf() method within a loop.
How to get all index in Java? ›- import java. util. List;
- public static void main(String[] args)
- List<Integer> values = List. of(5, 3, 4, 7, 6, 2, 9, 6);
- int item = 6;
- int index = values. indexOf(item);
- System. out. println(index); // 4.
To find the index of an item in an array in Swift, you can use the firstIndex(of:) method of the Array type. This method returns the index of the first element in the array that is equal to the given element or nil if no such element is found.