C# 学习笔记 10.可空类型,匿名方法,迭代器

1.可空类型

1.可空类型也是值类型,但是它包含了null值的值类型。

表示一个可空类型

int i = null;// 报错  无法将 null 转换为“int”,因为后者是不可以为 null 的值类型 

int? i = null; 编译通过 //但是c#中肯定没有int?这个类型,编译器会解释Nullable<int> 类型,即可空类型。

可空类型的定义是 public struct Nullable<T> where T : struct

//定义

 Nullable<int> value = 1;

2.空合并操作符 ??

如果左边是null就返回右边,反之返回左边。

  int? a1 = 10;
  int? a2 = null;
  int ?x = a2 ?? a1;

// string类型也可以使用??

string s1 = null;
string s2 = "s2";
string s = s1 ?? s2;

2.匿名方法

匿名方法是通过使用 delegate 关键字创建委托实例来声明的。

1.没有名字的方法,只能再函数定义的时候被调用,其它情况下不能调用。

  class Program
    {
        delegate void voteDelegate(string name);

        public void FriendVote(string name)
        {
            Console.WriteLine(name);
        }

        static void Main(string[] args)
        {
            voteDelegate va = new voteDelegate(new Program().FriendVote);
            va("kevin");

// 可以少写一个函数 FriendVote
            voteDelegate va2 = delegate (string name)
            {
                Console.WriteLine("hello "+name);

            };
            va2("kevin");
            Console.ReadKey();
        }

    }

2.匿名不具有复用性。不能再其它的地方被调用。

匿名方法会形成闭包。闭包会延迟外部变量的生命周期。

3.迭代器

迭代器要实现IEnumerable或者IEnumerable<T>接口。

接口中定义了一个GetEnumerator的方法用来返回迭代器,所以必须实现这个方法。

 class Program
    {

        static void Main(string[] args)
        {

            Friends friend = new Friends();

            foreach (Friend f in friend)
            {
                Console.WriteLine(f.Name);
            }


            Console.ReadKey();
        }

        public class Friend
        {
            private string name;
            public string Name
            {
                get { return name; }
                set { name = value; }
            }
            public Friend(string name)
            {
                this.name = name;
            }

        }

        public class Friends : IEnumerable
        {
            private Friend[] friendarray;
            public Friends()
            {
                friendarray = new Friend[]
                    {
                        new Friend("张三"),
                        new Friend("李四"),
                        new Friend ("王五")
                    };

            }

            public Friend this[int index]
            {
                get { return friendarray[index]; }
            }

            public int Count
            {
                get { return friendarray.Length; }
            }

            public IEnumerator GetEnumerator()
            {
                for(int index =0; index<friendarray.Length;index++)
                {
                    yield return friendarray[index];
                }
            }

        }
    }

 

 

 

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值