1、泛型
namespace GenericsDemo
{
class TestGenerics
{
static void Main(string[] args)
{
GenericsExample();
}
private void GenericsExample()
{
ClsGeneric<int> intGeneric = new ClsGeneric<int>(1000);
ClsGeneric<string> strGeneric = new ClsGeneric<string>("Voila");
ClsGeneric<float> fGeneric = new ClsGeneric<float>(23.38f);
ClsGeneric<double> dGeneric = new ClsGeneric<double>(444.4);
ClsGeneric<bool> bGeneric = new ClsGeneric<bool>(true);
}
}
public class ClsGeneric<T>
{
public ClsGeneric(T Type)
{
Console.WriteLine("T over here is {0} ", typeof(T).ToString());
}
}
}
2、迭代器
public class StringCollection : System.Collections.IEnumerable
{
string[] names = { "Tom", "Dick", "Harry”, "Ralph", "Jack", "Jill” };
public System.Collections.IEnumerator GetEnumerator()
{
for (int i = 0; i < names.Length; i++)
{
yield return names[i];
// In C#1.x you would have specified it using
// return names[i].GetEnumerator();
}
}
}
class TestStringCollection
{
static void Main()
{
// Create an instance
StringCollection strNames = new StringCollection();
foreach (string name in strNames)
{
System.Console.WriteLine(name);
}
Console.WriteLine("Press any key to continue...");
Console.ReadKey();
}
}
3、局部类
public partial class A
{
public void methodA()
{
// Code for methodA
}
}
public partial class A
{
public void methodB()
{
// Code for methodB
}
}
4、空类型
int? iVal = null;
if (iVal.HasValue == true)
{
System.Console.WriteLine("iVal = " + iVal.Value);
}
else
{
System.Console.WriteLine("iVal = Null");
}
5、匿名方法
public class frmNew : Form
{
public frmNew()
{
InitializeComponent();
btnNew.Click += delegate(object sender, EventArgs e)
{
MessageBox.Show(“New way of handling button click using anonymous methods");
};
}
}
// Declare a delegate
delegate void PrintHello(string str);
class TestAnonymous
{
static void Main()
{
PrintHello hello = new PrintHello(TestAnonymous.TestMethod);
hello(“Hello! Test!”);
}
}
static void TestMethod(string test)
{
System.Console.WriteLine(test);
}
6、属性的访问修饰符
public string StrMyName
{
get
{
return strMyName;
}
protected set
{
strMyName = value;
}
}
我思故我在