C# 2.0的新特色 第一部分
Anonymous Methods
在Java中有,看看就行了吧,当然在这个例子中还有了另一个新东西:partial。
Iterators
为了实现如下用法:
我们可以这样做:
比如:
然后就可以这样用了:
这是MSDN中的例子:
using System;
using System.Collections;
public class List
{
public static IEnumerable Power(int number, int exponent)
{
int counter = 0;
int result = 1;
while(counter++ < exponent)
{
result = result * number;
yield return result;
}
}
static void Main()
{
// Display powers of 2 up to the exponent 8:
foreach(int i in Power(2, 8))
Console.Write("{0} ", i);
}
}
Partial Classes
他可以让你把一个类放到两个文件中去。注意都得有关键字:partial
比如:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
button1.Click += delegate(object sender, EventArgs e)
{
// The following code is part of an anonymous method.
MessageBox.Show("You clicked the button, and " +
"This is an anonymous method!");
};
}
}
在Java中有,看看就行了吧,当然在这个例子中还有了另一个新东西:partial。
Iterators
为了实现如下用法:
foreach (OrderItem item in catalog)
{
// (Process OrderItem here.)
}
我们可以这样做:
Enumerator e = catalog.GetEnumerator();
while (e.MoveNext())
{
OrderItem item = e.Current;
// (Process OrderItem here.)
}
比如:
public class OrderCatalog
{
private ArrayList orderItems = new ArrayList();
public void Load()
{
// Fill collection for a test.
orderItems.Clear();
orderItems.Add(new OrderItem("Item 1"));
orderItems.Add(new OrderItem("Item 2"));
orderItems.Add(new OrderItem("Item 3"));
}
public IEnumerator<OrderItem> GetEnumerator()
{
foreach (OrderItem item in orderItems)
{
yield return item;
}
}
}
public class OrderItem
{
private string name;
public string Name
{
get { return name; }
}
public OrderItem(string name)
{
this.name = name;
}
}
然后就可以这样用了:
OrderCatalog catalog = new OrderCatalog();
catalog.Load();
foreach (OrderItem item in catalog)
{
MessageBox.Show(item.Name);
}
这是MSDN中的例子:
using System;
using System.Collections;
public class List
{
public static IEnumerable Power(int number, int exponent)
{
int counter = 0;
int result = 1;
while(counter++ < exponent)
{
result = result * number;
yield return result;
}
}
static void Main()
{
// Display powers of 2 up to the exponent 8:
foreach(int i in Power(2, 8))
Console.Write("{0} ", i);
}
}
Partial Classes
他可以让你把一个类放到两个文件中去。注意都得有关键字:partial
比如:
//在文件MyClass1.cs中
public partial class MyClass
{
public MethodA()
{...}
}
//在文件MyClass2.cs中
public partial class MyClass
{
public MethodB()
{...}
}