using System;
// 目的:泛型理解
/* 泛型支持继承和多态,因为泛型可以接受一个接口,通过该实验可以证明
* 接口泛型可以控制协变和抗变
* // 抗变
* public interface IB<in T>{
* void fun(T t);// 单可以有外部传入
* //T fun();//err 不能想外输出
* }
* 抗变:in 标识的T 不能向外输出,单可以有外部传入
* // 协变
* public interface IA<out T> where T:new() {
* T fun(); //能向外输出
* //void fun(T t);//err 不能有外部传入
* }
* 协变:out 标识的T 能向外输出,单是不能有外部传入
*
*/
namespace 泛型
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
A<B> ab = new A<B>();
ab.t = new C();
ab.t.Fun();
Console.ReadLine();
}
}
interface IA {
void Fun();
}
class A<T> where T:IA{
public T t;
void Fun() {
t.Fun();
}
}
class B : IA {
public virtual void Fun() {
Console.WriteLine("B Func");
}
}
class C:B
{
public override void Fun()
{
Console.WriteLine("C Func");
}
}
}
c#-泛型-多态泛型
最新推荐文章于 2021-06-30 09:36:21 发布