代码
using System;
// 协变
public interface IA<out T> where T:new() {
T fun();
//void fun(T t);//err
}
// 抗变
public interface IB<in T>{
void fun(T t);
//T fun();//err
}
class A:IA<C>{
public C fun(){
return new C();
}
}
class B:IB<C>{
public C c;
public void fun(C c){
this.c = c;
}
}
class C{
public int a = 5;
}
public class Fanxing{
public static void Main(){
Console.WriteLine("hello word");
A a = new A();
B b = new B();
C c1 = new C();
c1.a = 6;
b.fun(c1);
Console.WriteLine(a.fun().a);
Console.WriteLine(b.c.a);
}
}

本文深入解析了C#中的泛型协变和抗变特性,通过具体的代码示例展示了如何在接口中使用协变和抗变来增强类型的安全性和灵活性。文章详细解释了协变和抗变的定义、作用以及使用场景,为读者提供了理解和应用这些高级类型的指南。
986

被折叠的 条评论
为什么被折叠?



