• ylbtech-LanguageSamples-SimpleVariance


    ylbtech-Microsoft-CSharpSamples:ylbtech-LanguageSamples-SimpleVariance

     

    1.A,示例(Sample) 返回顶部

    SimpleVariance 示例程序演示在委托和接口中使用泛型类型时,C# 4.0 对协变和逆变的支持。 在 C# 3.0 中,泛型类型是固定的。 因此,本示例在 C# 4.0 中可正常编译,但在早期版本的 C# 中无法编译。

    程序首先声明两个简单类和两个委托:

    class  Animal { }
    class Cat : Animal { }
    
    delegate T Func1<out T>();
    delegate void Action1<in T>(T a);

    然后,实现这些委托并使用这些类:

    Func1<Cat> cat = () => new Cat();
    Action1<Animal> act1 = (ani) => { Console.WriteLine(ani); };

    再进行需要协变和逆变支持的分配:

    Func1<Animal> animal = cat;
    Action1<Cat> cat1 = act1;

    后面这一组分配在 C# 4.0 中可以正常工作,但在早期版本的 C# 中无法工作。 第一个分配演示协变,第二个分配演示逆变。

    通过新增的上下文关键字 outin,可以指定泛型类型是要传递到委托或接口方法中,还是要从委托或接口方法返回。

    1.B,SimpleVariance 示例代码(Sample Code)返回顶部

    1.B.1, Program.cs

    // 版权所有(C) Microsoft Corporation。保留所有权利。
    // 此代码的发布遵从
    // Microsoft 公共许可(MS-PL,http://opensource.org/licenses/ms-pl.html)的条款。
    //
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace SimpleVariance
    {
        class Animal { }
        class Cat: Animal { }
    
        class Program
        {
            // 要了解新的协变和逆变代码能够为您实现的功能
            // 尝试从以下两行代码中添加或删除这些内容:
            delegate T Func1<out T>();
            delegate void Action1<in T>(T a);
            
            static void Main(string[] args)
            {
                Func1<Cat> cat = () => new Cat();
                Func1<Animal> animal = cat;
    
                Action1<Animal> act1 = (ani) => { Console.WriteLine(ani); };
                Action1<Cat> cat1 = act1;
    
                Console.WriteLine(animal());
                cat1(new Cat());
            }
    
            
        }
    }
    View Code

    1.B.2,

    1.B.EXE,

    SimpleVariance.Cat
    SimpleVariance.Cat
    请按任意键继续. . .

    1.B,

    1.C,下载地址(Free Download)返回顶部
    warn 作者:ylbtech
    出处:http://ylbtech.cnblogs.com/
    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
  • 相关阅读:
    雷观(四):手机不可能取代电脑
    小雷FansUnion:我有了第一个付费客户(第一个徒弟)
    小雷FansUnion:我有了第一个付费客户(第一个徒弟)
    博客搬家算法伪码
    博客搬家算法伪码
    MySQL数据库定时自动备份脚本
    Java实现 LeetCode 386 字典序排数
    Java实现 LeetCode 386 字典序排数
    Java实现 LeetCode 386 字典序排数
    Java实现 LeetCode 385 迷你语法分析器
  • 原文地址:https://www.cnblogs.com/ylbtech/p/4197323.html
Copyright © 2020-2023  润新知