您的位置:首页 > 编程语言 > C#

C#_Delegate_泛型

2015-11-26 20:12 549 查看
//委托是一种数据类型 将方法作为参数进行传递

//我们定义委托 需要定义 委托的 返回值以及参数类型、个数

//利用delegate来定义

  public delegate void GetSthDelegate();

  void static Main()

  {

    GetSthDelegate gd=new GetSthDelegate(Function1);   

    //GetSthDelegate gd=Function1; 

    gd();  //或者

    gd.Invoke();

  }

  static void Function1()

  {

    print("This is f1.");

  }

//委托类型当作参数来使用

//----------------------------Action委托

  Action 系统预定义的委托类型    无参数 无返回值

  Action<int> a;  //定义了一个委托变量 有一个int参数 无返回值

  Action<string> a; //~~~~~~~~~~~~ ~~~~string~~ ~~~~

  //系统自动匹配方法

  //Action 无返回值

  Action<int,int> a; //定义了一个有两个int参数委托变量 无返回值

  //最大支持 16个参数

//---------------------多播委托--------------

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _11泛型约束
{
class Program
{
static void Main(string[] args)
{
//在自定泛型之后   约束T可传入参数的数据类型

//委托是针对一个方法多态   而接口可以针对n多个方法多态

//pre练习
//List<int> listInt = new List<int>();
//listInt.Add(10);
//listInt.Add(4);
//listInt.Add(6);
//listInt.Sort();
//foreach (int item in listInt)
//{
//    Console.WriteLine(item);
//}

#region list排序

//List<Person> listPerson = new List<Person>() {
//    new Person(){Name="wang",Age=32},
//    new Person(){Name="ling",Age=23}
//};
////要实现排序   需要实现IComparable
//listPerson.Sort();
//foreach (Person item in listPerson)
//{
//    Console.WriteLine("{0},{1}", item.Age, item.Name);
//}
//Console.WriteLine("--------------------------------------------");
////实现排序   也可以传递比较器
//listPerson.Sort(new AscByAge());
//foreach (Person item in listPerson)
//{
//    Console.WriteLine("{0},{1}", item.Age, item.Name);
//}
#endregion

//泛型约束         在泛型后面  添加   where   T   :     struct       //struct代表值类型

//不能限制具体的值类型
MyClass<double> testDou = new MyClass<double>();

//在泛型后面添加   where T : class    //class代表T为引用类型
//在后面添加  where T  : IComparable     //代表T必须为实现某接口的类型
TestClass<string> testStr = new TestClass<string>();

}
}

//使用泛型约束   约束  T 只能是  值类型
class MyClass<T> where T : struct
{

}

//使用泛型约束   约束  T只能是 引用类型
class TestClass<T> where T : class
{

}

//约束  T 必须实现  IComparable
class TestClass2<T> where T : IComparable
{

}

//比较器
class AscByAge : IComparer<Person>
{
public int Compare(Person x, Person y)
{
return y.Age - x.Age;
}
}

//实现比较的泛型接口   传递的就是Person类型
class Person:IComparable<Person>
{
private int _age;
public int Age
{
get { return _age; }
set { _age = value; }
}
private string _name;
public string Name
{
get { return _name; }
set { _name = value; }
}
//实现IComparable<Person>   实现泛型接口
public int CompareTo(Person other)
{
// throw new NotImplementedException();
return this.Age - other.Age;
}
}
}


泛型约束
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: