泛型声明实例:
class MyStack <T>
{
int StackPointer = 0;
T [] StackArray;
public void Push(T x) {....}
public T Pop(){...}
}
T代表类型的占位符,也不一定要是字母T,可以是任何标识符。T又称为类型参数。
class SomeClass <T1, T2>
{
public T1 SomeVar = new T1();
public T2 OtherVar = new T2();
}
SomeClass<short, int> myInst;
myInst = new SomeClass<short, int>();
var mySc = new SomeClass<short, int>();
用var关键词使编译器使用类型引用;
只有符合约束的实参才能用于类型参数。通过where子句来实现约束。
class MyClass <T1, T2, T3>
where T2 : Customer
where T3 : IComparable
{...}
5种类型约束:
类名:只有这个类型的类或从它继承的类才能用作类型实参;
class:任何引用类型,包括类、数组、委托和接口都可以用作实参;
struct:任何值类型都可以被用作类型实参;
Interfacename:只有这个接口或实现这个接口的类型才能用作实参;
new():任何带有无参公共构造函数的类型都可以用作实参,这叫做构造函数约束。
泛型结构:
struct PieceOfData<T>
{
public PieceOfData(T value) {_Data = value; }
private T _Data;
public T Data
{
get { return _Data; }
set { _Data = value; }
}
}
泛型接口:
interface IMyIfc<T>
{
T ReturnIt(T inValue);
}
class Simple<S> : IMyIfc<S>
{
public S ReturnIt(S inValue)
{
return inValue;
}
}
class Simple2 : IMyIfc<int>, IMyIfc<string>
{
public int ReturnIt(int inValue)
{ return inValue; }
public string ReturnIt(string inValue)
{ return inValue; }
}
实现泛型类型接口时,必须没有可能的类型实参组合会在类型中产生两个重复的接口。
泛型委托:
delegate R MyDelegate<T, R>(T value);
delegete void MyDelegate<T>(T value);
var myDel = new MyDelegate<string>(Simple.PrintString);
泛型方法:
public void PrintData<S, T>(S p) where S: Person{...}
泛型类的扩展方法:
必须声明为static;
必须是静态类的成员;
第一个参数类型中必须有关键字this,后面是扩展的泛型类的名字;
public static void Print<T>(this Holder<T> h){...}
匿名类型:
var student = new {LName="Jones", FName="Mary", Age=19, Major="History"};
var student = new { Age=19, Major, Other.Name };
赋值形式;标识符形式;成员访问表达式;
方法语句:
int[] numbers = {2, 5, 28, 31};
var numsMethod = numbers.Where(x => x < 20);
int[] arr1 = {10, 11, 12, 13};
var query = from item in arr1
where item < 13
select item;
int[] numbers = { 2, 12, 5, 15 };
IEnumerable<int> LowNums = from n in numbers
where n < 10
select n;
join子句
var query = from s in students
join c in studentsInCourses on s.StID equals c.StID;
from子句
var groupA = new[]{3, 4, 5, 6};
var groupB = new[]{6, 7, 8, 9};
var someInts = from a in groupA
from b in groupB
where a > 4 && b <= 8
select new {a, b, sum = a + b };
let子句:接受一个表达式的运算并且把它赋值给一个需要在其他运算中使用的标识符;
var someInts = from a in groupA
from b in groupB
let sum = a + b
where sum == 12
select new {a, b, sum };
使用LINQ to XML的LINQ查询:
XDocument xd = XDocument.Load("SimpleSample.xml");
XElement rt = xd.Element("MyElements");
var xyz = from e in rt.Elements()
where e.Name.toString().Length == 5
select e;