You can use generics to define interfaces. Methods in interfaces can contain generic parameters.
The following is an example of a generic interface:
Public interface icomparable <t> {int compareto (t other );}
For the implementation of a person class:
Public class person: icomparable <person> {public int compareto (person OBJ) {return this. lastname. compareto (other. lastname );}}
In addition to defining generic types, you can also define generic methods. In generic methods, generic types are defined using method declarations.
The following shows an exchange generic method:
Void swap <t> (ref t x, ref t y) {T temp; temp = x; X = y; y = temp ;}
There are two methods for calling generic methods:
1. Assign the generic type to the method call
Int I = 4; Int J = 5; Swap <int> (Ref I, ref J );
Or call it directly like a non-generic method, because the C # compiler will obtain the parameter type by calling the swap method.
Int I = 4; Int J = 5; swap (Ref I, ref J );
The following example uses the generic method to accumulate all elements in the set.
Using system; using system. collections. generic; using system. collections; using system. LINQ; using system. text; namespace genericmethod {public class account {private string name; Public string name {get {return name ;}} private decimal balance; Public decimal balance {get {return balance ;}} public Account (string name, decimal balance) {This. name = Name; this. balance = balance ;}}// use the foreach statement in the traditional method to iterate all account objects public static class algorithm {public static decimal accumulatesimple (ienumerable e) {decimal sum = 0; foreach (account A in E) {sum + =. balance;} return sum ;}} class program {static void main (string [] ARGs) {list <account> accounts = new list <account> (); accounts. add (New Account ("Christian", 1500); accounts. add (New Account ("Sharon", 2200); accounts. add (New Account ("Katie", 1800); decimal amount = algorithm. accumulatesimple (Accounts); console. writeline (amount. tostring (); console. readline ();}}}
When using the traditional method above, there will be a problem. It can only be applied to account objects.
Foreach (account A in E)
Extend this method to apply to all objects
// Enhanced generic method public class account: iaccount {//...} public interface iaccount {decimal balance {Get;} string name {Get ;}} public static class algorithm {public static decimal accumulatesimple <taccount> (ienumerable <taccount> Coll) Where taccount: iaccount {decimal sum = 0; foreach (taccount A in Coll) {sum + =. balance;} return sum ;}}
Two methods can be used to call this generic method:
Decimal amount = algorithm. accumulate <account> (Accounts );
Or:
Decimal amount = algorithm. accmulate (Accounts );