Posted on 2015-07-29 20:23
Onway 阅读(360)
评论(0) 编辑 收藏 引用 所属分类:
使用说明
因为某些原因,一直用的都是.NET2,但渣也总得有些追求是不,说不定哪天就用上了呢?
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplicationTest
{
/*
* 变体泛型
*
* .NET4,在泛型接口类型或者泛型委托类型里面,
* 被关键字in声明的泛型参数,其类型可以从父类向子类逆变,只能用作输入参数
* 被关键字out声明的泛型参数,其类型可以从子类向父类协变,只能用于返回值
* 整个泛型类型是不限于用作输入参数还是作为返回值
*
* interface IType_IN_OUT<in T1, out T2>
* IType_IN_OUT<Farmer, Person> farmerPersonType = null;
* IType_IN_OUT<Person, Farmer> personfarmerType = null;
* farmerPersonFinder = personFarmerFinder;
*
* 为什么不支持“变体”class呢?跟字段有关系么?
*/
class Program
{
static void Main(string[] args)
{
IType_IN<Person> person_in = null;
IType_IN<Farmer> farmer_in = null;
farmer_in = person_in;
Greeting(person_in);
Console.WriteLine(GetTypeIn() == null);
IType_OUT<Person> person_out = null;
IType_OUT<Farmer> farmer_out = null;
person_out = farmer_out;
Greeting(farmer_out);
Console.WriteLine(GetTypeOut() == null);
Finder_IN<Person> personFinderIn = p => Console.WriteLine(p.GetType());
Finder_IN<Farmer> farmerFinderIn = f => Console.WriteLine(f.GetType());
farmerFinderIn = personFinderIn;
Greeting(personFinderIn);
Console.WriteLine(GetFarmerFinder().GetType());
Finder_OUT<Person> personFinderOut = () => new Person();
Finder_OUT<Farmer> farmerFinderOut = () => new Farmer();
personFinderOut = farmerFinderOut;
Greeting(personFinderOut);
Console.WriteLine(GetPersonFinder().GetType());
Finder_IN_OUT<Farmer, Person> farmerPersonFinder = f => new Person();
Finder_IN_OUT<Person, Farmer> personFarmerFinder = p => new Farmer();
farmerPersonFinder = personFarmerFinder;
// interface IType_IN_OUT<in T1, out T2>
IType_IN_OUT<Farmer, Person> farmerPersonType = null;
IType_IN_OUT<Person, Farmer> personfarmerType = null;
farmerPersonType = personfarmerType;
Console.ReadKey();
}
static void Greeting(IType_OUT<Person> person)
{
Console.WriteLine(person == null);
}
static void Greeting(IType_IN<Farmer> farmer)
{
Console.WriteLine(farmer == null);
}
static IType_OUT<Person> GetTypeOut()
{
IType_OUT<Farmer> farmer = null;
return farmer;
}
static IType_IN<Farmer> GetTypeIn()
{
IType_IN<Person> person_IN = null;
return person_IN;
}
static void Greeting(Finder_OUT<Person> personFinder)
{
Console.WriteLine(personFinder().GetType());
}
static void Greeting(Finder_IN<Farmer> farmerFinder)
{
Console.WriteLine(farmerFinder.GetType());
}
static Finder_OUT<Person> GetPersonFinder()
{
Finder_OUT<Farmer> farmerFinder = () => new Farmer();
return farmerFinder;
}
static Finder_IN<Farmer> GetFarmerFinder()
{
Finder_IN<Person> person = p => Console.WriteLine(p.GetType());
return person;
}
}
interface IType_OUT<out T>
{
}
interface IType_IN<in T>
{
}
interface IType_IN_OUT<in T1, out T2>
{
}
delegate T Finder_OUT<out T>();
delegate void Finder_IN<in T>(T t);
delegate T2 Finder_IN_OUT<in T1, out T2>(T1 t1);
class Person
{
}
class Farmer : Person
{
}
}