您的位置:首页 > 编程语言 > C#

C#迭代重载等

2016-03-07 20:14 447 查看
迭代器

迭代器是作为一个容器,将要遍历的数据放入,通过统一的接口返回相同类型的值

迭代器代码使用 yield return 语句依次返回每个元素。yield break 将终止迭代

类中实现多个迭代器。每个迭代器都必须像任何类成员一样有唯一的名称

迭代器的返回类型必须为

Ienumerable(整形接口)、IEnumerator、IEnumerable<T> 或 IEnumerator<T>(泛型接口)

//为整数列表创建迭代器
public class SampleCollection{
public int[] items = new int[5] { 5, 4, 7, 9, 3 };
public System.Collections.IEnumerable BuildCollection() {
for (int i = 0; i < items.Length; i++) {
yield return items[i];
}
}
}
class Program {
static void Main(string[] args) {
SampleCollection col = new SampleCollection();
foreach (int i in col.BuildCollection())//输出集合数据
{
System.Console.Write(i + " ");
}
for (;;) ;
}
}


问题:Ienumerator和Ienumerable区别?

IEnumerator<T>泛型接口如何实现?

类型比较

封箱和拆箱子:封箱是把值类型转换为System.Object,或者转换为由值类型的接口类型。拆箱相反。

装箱和拆箱是为了将值转换为对象

struct MyStruct
{
public int Val;
}
class Program
{
static void Main(string[] args) {
MyStruct valType1 = new MyStruct();
valType1.Val = 1;
object refType = valType1;
//封箱操作,可以供传递用
MyStruct valType2 = (MyStruct)refType;
//访问值类型必须拆箱
Console.WriteLine(valType2.Val);//输出1
for (;;) ;
}


Is运算符语法:

<operand>is<type>同类型返回true,不同类型返回false

As运算符语法:

<operand>is<type>把一种类型转换为指定的引用类型

运算符重载



public class Add2 {
public int val {
get; set;
}
public static Add2 operator ++(Add2 op1) {
op1.val = 100;//设置属性
op1.val = op1.val + 2;
return op1;
}
}
class Program {
static void Main(string[] args) {
Add2 add = new Add2();
add++;
Console.WriteLine(add.val);//输出102
for (;;) ;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: