(精华)2020年8月11日 C#基础知识点 匿名类的使用(object,var,dynamic)

#region 3.0出了个匿名类  
                {
                    Console.WriteLine("*****************匿名类**************");
                    Student student = new Student()
                    {
                        Id = 1,
                        Name = "Richard",
                        Age = 25,
                        ClassId = 2
                    };
                    student.Study();
                    //-------------------------匿名类的使用--------------------------
                    object model = new//.net 3.0    
                    {
                        Id = 2,
                        Name = "undefined",
                        Age = 25,
                        ClassId = 2,
                        Teacher = "Richard"
                    };

                    //匿名类无法访问属性值
                    //Console.WriteLine(model.Id); //object中肯定有Id/Name,C#是强类型语言,编译器不认可,;
                    //Console.WriteLine(model.Name);

                    //--------------------------dynamic避开编译器检查 (4.0)-------------------
                    //(动态类型),可以避开编译器的检查
                    dynamic dModel = new//
                    {
                        Id = 2,
                        Name = "undefined",
                        Age = 25,
                        ClassId = 2
                    };

                    dModel.Id = 134;
                    Console.WriteLine(dModel.Id);
                    Console.WriteLine(dModel.Name);
                    // Console.WriteLine(dModel.Js);// 会报异常
                    //----------------------------var 语法糖--------------------------
                    Console.WriteLine("&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&");
                    var model1 = new //不能声明方法
                    {
                        Id = 2,
                        Name = "undefined",
                        Age = 25,
                        ClassId = 2,
                        Teacher = "Richard"
                    };
                    Console.WriteLine(model1.Id);
                    Console.WriteLine(model1.Name);
                    //Console.WriteLine(model1.jk);
                    // model1.Id = 3; // 属性是只读不能修改
                    int i2 = 2;
                    var i1 = 1;//var就是个语法糖,由编译器自动推算
                    var s = "代码男孩";
                    //var声明的变量必须初始化,必须能推算出类型
                }
                #endregion

你可能感兴趣的:(C#,c#)