深入理解 c# 第十四章 使用鸭子类型访问Count属性 鸭子类型

    class DuckTypedCount
    {
        static void PrintCount(IEnumerable collection)
		//collection {System.Collections.BitArray}  Count = 2 Count = 3
        {
            dynamic d = collection;
			//d {System.Collections.BitArray}  {System.Collections.Generic.HashSet<int>}
			//{System.Collections.Generic.List<int>}
            int count = d.Count;
			//count 10 2 3
            Console.WriteLine(count);
			
        }

        static void Main()//使用鸭子类型访问Count属性  鸭子类型
        {
            PrintCount(new BitArray(10));
            PrintCount(new HashSet<int> { 3, 5 });
            PrintCount(new List<int> { 1, 2, 3 });
        }
    }


  有些时候,我们知道在执行时可以使用某个具有特殊名称的成员,但我们无法确切地告诉编译器
这个成员,因为这将取决于具体的类型。只是用普通的方法和属性替代了操作符。  
  通常我们可以捕获接口或抽象基类的共性。操作符无法实现捕获接口或抽象基类的共性,但对于
方法和属性来说却是十分常见的方法。
  鸭子类型允许我们在访问Count时不必执行类型检查。
  PrintCount方法与集合初始化列表一样,限制参数必须实现IEnumerable,原因是:它通常说明
我们最终使用的Count属性是合适的。测试用的集合为BitArray(只实现了ICollection)、HashSet<int>
(只实现了ICollection<int>)和List<int>(两者都实现了),它们都可以在执行时找到正确的属性。


输出
10
2
3

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值