语法糖(Syntactic sugar),也译为糖衣语法,是由英国计算机科学家彼得·约翰·兰达(Peter J. Landin)发明的一个术语,指计算机语言中添加的某种语法,这种语法对语言的功能并没有影响,但是更方便程序员使用。通常来说使用语法糖能够增加程序的可读性,从而减少程序代码出错的机会。需要声明的是“语法糖”这个词绝非贬义词,它可以给我们带来方便,是一种便捷的写法,编译器会帮我们做转换;而且可以提高开发编码的效率,在性能上也不会带来损失。
- private string _Name;
- public string Name
- {
- get { return _Name; }
- private set { _Name = value; }
- }
-
- private int _Age;
- public int Age
- {
- get { return _Age; }
- private set { _Age = value; }
- }
简化之后的的写法
- public string Name { get; set; }
- public int Age { get; private set; }
- class MyClass
- {
- //定义委托
- public delegate void TestDelegate(string str);
- //义委托方法
- public void Method(string str)
- {
- Console.WriteLine(str);
- }
-
- public void UseDelegate(TestDelegate d, string str)
- {
- d(str);
- }
- }
- //调用委托
- MyClass mc = new MyClass();
- //调用定义的委托方法
- mc.UseDelegate(new MyClass.TestDelegate(mc.Method), "Hello!");
- //使用匿名委托
- mc.UseDelegate(delegate(string str)
- {
- Console.WriteLine(str);
- }, "Hello!");
- //使用Lambda表达式
- mc.UseDelegate(s =>
- {
- Console.WriteLine(s);
- }, "Hello!");
- List<string> ListString = new List<string>();
- ListString.Add("a");
- ListString.Add("b");
- ListString.Add("c");
简化之后的写法
- List<string> ListString = new List<string>()
- {
- "a",
- "b",
- "c"
- };
2.取List中的值
未简化的写法
- foreach (string str in ListString)
- {
- Console.WriteLine(str);
- }
简化之后的写法
ListString.ForEach(s => Console.WriteLine(s));
- SqlConnection conn = null;
- try
- {
- conn = new SqlConnection("数据库连接字符串");
- conn.Open();
- }
- finally
- {
- conn.Close();
- conn.Dispose();
- }
使用Using写法
- using (SqlConnection conn=new SqlConnection("数据库连接字符串"))
- {
- conn.Open();
- }
- foreach (var item in collection)
- {
- }
- string sex = "男";
- int result = sex == "男" ? 1 : 0;//如果sex等于“男”result等于1,否则result等于0.
(??)两个问号的形式
- string sex = null;
- string s = sex ?? "未知";//左边的变量如果为null则值为右边的变量,否则就是左边的变量值
- class User
- {
- public int ID { get; set; }
- public string Name { get; set; }
- }
未简化的写法
- User u = new User();
- u.ID = 1;
- u.Name = "PanPan";
简化之后的写法
- User u = new User()
- {
- ID=1,
- Name="PanPan"
- };
- //定义扩展方法
- public static class StringExtensions
- {
- public static bool IsEmpty(this string str)
- {
- return string.IsNullOrEmpty(str);
- }
- }
- //调用扩展方法
- string temp="123";
- bool result = temp.IsEmpty();
var NoName = new { Name="PanPan",Age=20 };
- //定义方法
- private void haha(bool bol=false, int ab=1)
- {
- }
- //调用方法
- haha(bol: true);
- Dictionary<string, string> dic = new Dictionary<string, string>()
- {
- {"1","admin"},{"2","PanPan"}
- };
- dynamic dy = "string";
- Console.WriteLine(dy.GetType());
- //输出:System.String
- dy = 100;
- Console.WriteLine(dy.GetType());
- //输出:System.Int32