C # Introduction to generic interfaces of generic methods,
Here, I want to add the necessary knowledge to those who want to have a deeper understanding in. Net!
The following describes generic methods, generic interfaces, and generic classes:
1. generic classes
Declare a class
Using System; using System. collections. generic; using System. linq; using System. text; namespace AutofacDemo {// interface IFanXingable <T> {T SayNumber (T t);} // generic class public class FanXing <T> // where T: class, new () {T [] arryStrings = new T [] {}; // The indexer public T this [int index] {get {return arryStrings [index];} set {arryStrings [index] = value ;}// generic method public T Add <T> (T str) {return str ;}}}
Call where it is needed
Using System; using System. codeDom; using System. collections. generic; using System. data. common; using System. linq; using System. reflection; using System. security. authentication. extendedProtection; using System. text; using Autofac. configuration; namespace AutofacDemo {
// Test the generic type
Public class Person
{
Public string Name {get; set ;}
Public int Age {get; set ;}
Public void Add <T> (T t)
{
Console. WriteLine (t );
}
}
Static void Main (string [] args) {// instantiate FanXing <string> fanXing = new FanXing <string> (); fanXing [0] = "aaa1 "; fanXing [1] = "aaa2"; fanXing [2] = "aaa3"; fanXing [3] = "aaa4 "; fanXing <int> fanXingInt = new FanXing <int> (); fanXingInt [0] = 1; fanXingInt [2] = 2; fanXingInt [3] = 4; fanXingInt [4] = 3; FanXing <Person> fanXingClass = new FanXing <Person> (); fanXingClass [0] = new Person () {Name = "guo ", age = 21}; fanXingClass [0] = new Person () {Name = "yang", Age = 20 }; // method generic is the abstract data type of the data type. It is the abstract Console of the object. readKey ();}}}
How to Implement generic interfaces? This is also simple. Declare a class and directly inherit the interface you have defined.
// Implement the public class MyClass: IFanXingable <Int32> {public int SayNumber (int t) {return t ;}}
What about method generics? It is simpler to get a generic method in the base class and implement it when the subclass is inherited. However, I would like to think about the situations where I used them, for example, when querying by PAGE, There Is A sort by age? Or sort by ID or by date? This is an uncertain factor, so here is the most appropriate place to use generic methods!
This article is original and cannot be reproduced without consent!