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

C#开发 —— 高级应用

2014-07-07 15:56 295 查看
迭代器


可以返回相同类型的值的有序序列的一段代码,可用作方法,运算符或get访问器的代码体

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

迭代器的返回类型必须为 IEnumerable 或 IEnumerator 中的任意一种


对IEnumerator 接口实现GetEnumerator方法:



namespace Test01
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public class Family : System.Collections.IEnumerable
{
string[] MyFamily ={ "父亲","母亲","弟弟","妹妹"};
public System.Collections.IEnumerator GetEnumerator()
{
for (int i = 0; i < MyFamily.Length; i++)
{
yield return MyFamily[i];
}
}
}
private void Form1_Load(object sender, EventArgs e)
{
Family myfamily = new Family();
foreach (string str in myfamily)
{
richTextBox1.Text += str + "\n";
}
}
}
}



分部类


可以将类,结构或接口的定义拆分到两个或多个源文件中

定义分布类需要使用 partial 关键字,分部类的每个部分都必须包含一个partial关键字,并且其声明必须与其他部分位于同一命名空间

在设置分部类时,各个分部必须有相同的可访问性

namespace Test04
{
class Program
{
partial class Mclass
{
public void Hello()
{
Console.WriteLine("用一生下载你");
}
}
partial class Mclass
{
public void Hi()
{
Console.WriteLine("芸烨湘枫");
}
}
static void Main(string[] args)
{
Mclass myclass = new Mclass();
myclass.Hello();
myclass.Hi();
Console.ReadLine();
}
}
}




namespace Test03
{
public class Year : System.Collections.IEnumerable//实现迭代器的类
{
string[] season = { "Spring", "Summer", "Autumn", "Winter" };

public System.Collections.IEnumerator GetEnumerator()
{
for (int i = 0; i < season.Length; i++)
{
yield return season[i];
}
}
}
class Program
{
static void Main(string[] args)
{
Year y = new Year();
// 使用迭代器
foreach (string s in y)
{
System.Console.Write(s + " ");
}
Console.ReadLine();
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: