C#中的自动属性、隐式类型var、对象初始化器与集合初始化器、扩展方法

1.自动属性(Auto-Implemented Properties)

//以前的写法 .net2.0
private string _userName;
public string UserName
{
     get { return _userName; }
     set { _userName= value; }
}
//现在 只适合3.5以上
 public string_userName {get;set;}

2.隐式类型var

   它是在编译已经能确定变量的类型,是根据后面的值自动推断类型,编译时把推断的类型替换掉var

看如下代码:
var v = new { Name="Tom",Age="18",Email="Tom@163.com" };
Console.WriteLine(v.Name);
Console.WriteLine(v.Age);
Console.WriteLine(v.Email);
Console.ReadLine();
//var  v.Name=”小明” ,隐式类型只能读取,不能赋值

3.对象初始化器与集合初始化器

对象初始化器

//写法一 DemoTest person = new  DemoTest { Name="xiaoming",Age=18,Sex="boy"};
//写法二 DemoTest person = new  DemoTest("123") { Name="xiaoming",Age=18,Sex="boy"};
//二种写法都在什么时候用? 
//写法一 是在调用类的默认构造函数时用
//写法二 是在调用类的默认有参构造函数时用

集合初始化器

List<DemoTest> list= new List<DemoTes> {
new DemoTest(){ Age=18,Name="xiaoming",Sex="boy"},
new DemoTest(){ Age=19,Name="xiaohua",Sex="girl"}
          };

4.扩展方法

static void Main(string[] args)
 {
       List<string> list = new List<string>();
       list.Contains//转到定义
}

这些带向下箭头的都是扩展的,那么我们转到定义(f12)看下,这个扩展定义在Enumerable类里面,是不是跟大家想的不

一样?一般都是转到List<T>本类里面,所以所有的扩展方法,都在静态类中

我们要写扩展方法的主要目的是什么?

当一个类型已经写好之后,需要给这个类型加一些方法,但是加这个方法的时候不能修改类型,不能修改这个类的源代码,那么大家会想直接修改源代码不就行了,假如.net2.0以前的版本list有一些方法是一个版本,你要是修改了可能有不兼容的问题

下面我们就自己写一个扩展方法

class Program
    {
        static void Main(string[] args)
        {

            //给NewClass加个扩展方法,输出18
            NewClass newclass = new NewClass();
            newclass.Age = 18;
            newclass.ShowMessage();
            Console.ReadKey();
            
        }
    } 
   public class NewClass
    {
        public string Name
        {
            get;
            set;
        }
        public int Age
        {
            get;
            set;
        }
        public string Email
        {
            get;
            set;
        }
        public void SayHello()
        {
            Console.WriteLine("Hello");
        }
    }

      //1.创建一个静态类
    public static class DemoTest
    {
        public static void ShowMessage(this NewClass newclass)//这里必须加this,不加就是普通的方法
        {
            Console.WriteLine(newclass.Age);
        }
    }

下面我们给string加一个扩展方法:

class Program
    {
        static void Main(string[] args)
        {
            string str = "Hello";
            int result = str.GetLength();
            Console.WriteLine(result);
            Console.ReadKey();

        }
    }
    //1.创建一个静态类
    public static class DemoTest
    {
        public static int GetLength(this string str)
        {
            //扩展方法不能访问类型中私有成员
            return str.Length;
        }
    }

接下来我们用反编译看下:

扩展方法只是看起来像是某个对象的方法,从反编译我们可以看出实际上根本不是该对象的方法,其实就是调用了某个静态类中的方法。

原文地址:https://www.cnblogs.com/qinyi173/p/4692670.html