public class Hero { private string name; public string Name { get { return name; } set { name = value; }
} }
自动属性:
1 2 3 4
public class Hero { public string Name { get; set; } }
附带其它操作:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
public class Hero { private string name; public string Name { get {return name;} set { if(value.Length <= 10) { name = value; } } } }
扩展方法
定义扩展方法:
1 2 3 4 5 6 7 8 9
public static class Ext { public static int ToInt(this string t) { int id; int.TryParse(t, out id); return id; } }
则可以这样调用:
1 2
string a = "1000"; int i = a.ToInt ();
初始化器
定义有一个这样的类:
1 2 3 4 5 6
class Hero { public int id; public string name; public int lv; }
对象初始化器:
1
Hero hero = new Hero (){ id = 10, name = "HeroA", lv = 1 };
集合初始化器:
1 2 3 4 5 6 7 8 9 10 11 12 13
List<Hero> Heroes = new List<Hero> { new Hero(){ id = 10, name = "HeroA", lv = 1 }, new Hero(){ id = 11, name = "HeroB", lv = 1 }, new Hero(){ id = 12, name = "HeroC", lv = 1 }, };
Dictionary<int, Hero> HeroesDict = new Dictionary<int, Hero> { { 10, new Hero(){ id = 10, name = "HeroA", lv = 1 } }, { 11, new Hero(){ id = 11, name = "HeroB", lv = 1 } }, { 12, new Hero(){ id = 12, name = "HeroC", lv = 1 } }, };
匿名类型
1 2 3 4 5
var h1 = new { name = "HeroA", lv = 1 }; var h2 = new[] { new { name = "HeroA", lv = 1 }, new { name = "HeroB", lv = 2 } };
public class HelloClass { public string Hello() { return "HELLO"; } public string HelloToName(string name) { return "HELLO " + name; } public string HelloToNameMulti(string name, int times) { string ret = "HELLO"; for (int i = 0; i < times; i++) { ret = ret + " " + name; } return ret; } }
HelloClass h = new HelloClass (); Func<string> f1 = h.Hello; Func<string,string> f2 = h.HelloToName; Func<string,int,string> f3 = h.HelloToNameMulti;