添加Lesson17
This commit is contained in:
@@ -0,0 +1,10 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net8.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
</PropertyGroup>
|
||||
|
||||
</Project>
|
||||
@@ -0,0 +1,53 @@
|
||||
namespace Lesson17_协变逆变练习
|
||||
{
|
||||
//协变
|
||||
delegate T TestOut<out T>();
|
||||
//逆变
|
||||
delegate void TestIn<in T>(T t);
|
||||
|
||||
class Father
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
class Son : Father
|
||||
{
|
||||
|
||||
}
|
||||
internal class Program
|
||||
{
|
||||
static void Main(string[] args)
|
||||
{
|
||||
#region 练习题一
|
||||
//请简述协变逆变有什么作用
|
||||
|
||||
//协变逆变是用来修饰泛型替代符的 只存在于泛型接口和泛型委托中
|
||||
//1.协变 用 out 修饰 只能作为返回值 不能作为参数
|
||||
//2.逆变 用 in 修饰 只能作为参数 不能作为返回值
|
||||
|
||||
//遵循里氏替换原则 用out和in修饰的泛型委托如果类型是父子关系 那么可以相互装载
|
||||
// 协变:父类泛型委托变量 可以装 子类泛型委托实例
|
||||
// 逆变:子类泛型委托变量 可以装 父类泛型委托实例
|
||||
#endregion
|
||||
|
||||
#region 练习题二
|
||||
//请写出协变逆变的代码示例
|
||||
|
||||
TestOut<Son> s = () =>
|
||||
{
|
||||
return new Son();
|
||||
};
|
||||
|
||||
TestOut<Father> tf = s;
|
||||
Father f = tf();
|
||||
|
||||
TestIn<Father> iF = (value) =>
|
||||
{
|
||||
Console.WriteLine("接受到一个Father类型的参数");
|
||||
};
|
||||
TestIn<Son> iS = iF;
|
||||
iS(new Son());
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user