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];
}
}
}
}