Beispiel #1
0
 public void EndEdit()
 {
     using (new Log())
     {
         backup = ToImmutable();
     }
 }
        // 初始化
        public void Initial()
        {
            // 方式1
            var person = new Person();
            // 方式二
            Person p         = new();
            string firstName = "marson";
            string lastName  = "shine";

            var ps = new Person {
                FirstName = firstName,
                LastName  = lastName
            };
            var ps2 = new Person {
                FirstName = firstName,
                LastName  = lastName
            };

            // record 类型,常用语只读场景,表示不可变类型
            ImmutablePerson ip  = new(firstName, lastName);
            ImmutablePerson ip2 = new(firstName, lastName);

            Console.WriteLine($"FullName = {ip.FirstName} {ip.LastName}");
            Console.WriteLine($"record 类型比较 ip == ip2 : {ip == ip2}");
            Console.WriteLine($"record 类型比较 ip.HashCode() = {ip.GetHashCode()}; ip2.HashCode() = {ip2.GetHashCode()}; 相等性 : {ip.GetHashCode() == ip2.GetHashCode()}");
            ImmutablePerson ip3 = ip2;

            ip3.FirstName = "summer";
            Console.WriteLine($"ip2.FirstName = {ip2.FirstName} ip3.FirstName = {ip3.FirstName}");
            Console.WriteLine($"record 类型比较 ip.HashCode() = {ip.GetHashCode()}; ip2.HashCode() = {ip2.GetHashCode()}; 相等性 : {ip.GetHashCode() == ip2.GetHashCode()}");
            // class 类型比较
            Person p1 = new() { FirstName = "marsonshine", LastName = "shine" };
            Person p2 = new() { FirstName = "marsonshine", LastName = "shine" };

            Console.WriteLine($"class 类型比较 p1 == p2 : {p1 == p2}");
            Console.WriteLine($"class 类型比较 ps.HashCode() = {ps.GetHashCode()}; ps2.HashCode() = {ps2.GetHashCode()}; 相等性 : {ps.GetHashCode() == ps2.GetHashCode()}");

            // record 上的 with 关键字
            // 可以指定属性必须和选填,在构造函数参数体现是必填
            // 选填是跟以前属性写法一样
            // 如果你想在原来的类型下对增加一些属性值,或者更改某些属性值,但是又不想破坏 record 带来的数据不变性,这个时候我们就可以使用 with 关键字,它会从已有的 record 类型按值复制出来一个新的 record 类型
            LoginResource login           = new("MarsonShine", "123$%^") { RememberMe = true };
            LoginResource loginLowercased = login with {
                UserName = login.UserName.ToLowerInvariant()
            };

            Console.WriteLine(login);
            Console.WriteLine(loginLowercased);

            var weight = 200;
            WeightMeasurement measurement = new(DateTime.Now, weight) {
                Pounds = WeightMeasurement.GetPounds(weight)
            };
        }
    }

    public class Person {
Beispiel #3
0
    public void _01()
    {
        // object-initializer 中可以对 init-only property 赋值
        var person01 = new ImmutablePerson
        {
            FirstName = "luo",
            LastName  = "tao",
        };

        // constructor 中可以对 init-only property 赋值
        var person02 = new ImmutablePerson("luo", "tao");

        // CS8852 init-only property 不能再被赋值
        // person01.FirstName = "owen";
    }
Beispiel #4
0
        public void TestCreateImmutablePerson()
        {
            var expected =
                "{\"FirstName\":\"John\",\"LastName\":\"Petersen\",\"Schools\":[{\"Institution\":\"Mansfield\",\"Year\":\"1988\",\"Degree\":\"BS\"},{\"Institution\":\"St. Joseph's\",\"Year\":\"1993\",\"Degree\":\"MBA\"},{\"Institution\":\"Rutgers\",\"Year\":\"2004\",\"Degree\":\"JD\"}]}";


            var schools = new List <ImmutableSchool>()
            {
                new ImmutableSchool()
                {
                    Degree = "BS", Institution = "Mansfield", Year = "1988"
                },
                new ImmutableSchool()
                {
                    Degree = "MBA", Institution = "St. Joseph's", Year = "1993"
                },
                new ImmutableSchool()
                {
                    Degree = "JD", Institution = "Rutgers", Year = "2004"
                }
            };

            var person = new ImmutablePerson()
            {
                FirstName = "John", LastName = "Petersen", Schools = schools.ToImmutableArray()
            };

            var actual = JsonConvert.SerializeObject(person);


            Assert.AreEqual(expected, actual);

            person.Schools = new ImmutableArray <ImmutableSchool>();

            Assert.AreEqual(3, person.Schools.Value.Length);

            person.Schools.Value[0].Degree = "XX";

            Assert.AreEqual("BS", person.Schools.Value[0].Degree);


            var x = new ImmutableArray <ImmutableSchool>();
        }
        static void Main(string[] args)
        {
            var jeff = new ImmutablePerson {
                FirstName = "Jeff",
                LastName  = "Winger"
            };

            // jeff.FirstName = "Geoff";

            var car = new ImmutableVehicle {
                Brand  = "Mazda MX-5 RF",
                Color  = "Soul Red Crystal Metallic",
                Wheels = 4
            };

            var repaintCar = car with {
                Color = "Polymetal Grey Metallic"
            };

            WriteLine("Original color was {0}, new color is {1}.",
                      arg0: car.Color, arg1: repaintCar.Color);

            var oscar = new ImmutableAnimal("Oscar", "Labrador");

            var(who, what) = oscar;                     // calls deconstruct method
            WriteLine($"{who} is a {what}.");
        }

        void UsingPacktLib9()
        {
            object[] passengers =
            {
                new FirstClassPassenger {
                    AirMiles = 1_419
                },
                new FirstClassPassenger {
                    AirMiles = 16_562
                },
Beispiel #6
0
        private static void RunRecordsDemo()
        {
            // work with records
            var pavel =
                new ImmutablePerson
            {
                FirstName = "Pavel",
                LastName  = "Talochka"
            };
            //init exception, Has to intialize when object create
            // pavel.FirstName = "Michail";

            var car = new ImmutableVehicle
            {
                Brand  = "BMW",
                Color  = "Soul Red Crystal Metallic",
                Wheels = 4
            };
            // cloning object
            var repaintingCar = car with {
                Color = "Pink"
            };

            WriteLine("Original color of the car is {0}, new color is {1}",
                      arg0: car.Color,
                      arg1: repaintingCar.Color);

            // immutable animal example

            var oscar = new ImmutableAnimal("Oscar", "Labrador");

            var(who, what) = oscar;
            WriteLine("{0} is a {1}.",
                      arg0: who,
                      arg1: what);
        }
Beispiel #7
0
        static void Main(string[] args)
        {
            Person Olli = new("Olli", new DateTime(1983, 12, 17));

            // ------------------------ page 180 - Record short version ------------------------
            var kosto = new ImmutableAnimal("Kosto", "Cat");

            var(name, species) = kosto;
            System.Console.WriteLine($"{name} is a {species}.");



            // ------------------------ page 179 - Init / Records ------------------------
            var Lenchen = new ImmutablePerson
            {
                FirstName = "Magdalena",
                LastName  = "Bergmann"
            };

            var car = new ImmutableVehicle
            {
                Wheels = 4,
                Brand  = "Ford",
                Color  = "Blue",
            };

            var repaintedCar = car with {
                Color = "Black"
            };

            // repaintedCar.Color = "Green";

            System.Console.WriteLine($"Original color was {car.Color}, repainted color is {repaintedCar.Color}.");



            // ------------------------ page 176 - Pattern Matching ------------------------

            /*
             * object[] passengers = {
             *  new FirstClassPassenger(){ AirMiles = 1_415},
             *  new FirstClassPassenger{ AirMiles = 16_562},
             *  new CoachClassPassenger{ CarryOnKG = 25.3},
             *  new CoachClassPassenger{ CarryOnKG = 0.3},
             *  new BusinessClassPassenger(),
             * };
             *
             * foreach (object passenger in passengers)
             * {
             *  decimal fligthCost = passenger switch
             *  {
             *      FirstClassPassenger p => p.AirMiles switch
             *      {
             *          > 35000 => 1500M,
             *          > 15000 => 1750M,
             *          _ => 2000M,
             *      },
             *
             *      BusinessClassPassenger => 1000M,
             *
             *      CoachClassPassenger p when p.CarryOnKG < 10.0 => 500M,
             *      CoachClassPassenger => 650M,
             *      _ => 800M,
             *  };
             *
             *  System.Console.WriteLine($"Flight costs {fligthCost:C} for {passenger}");
             * }
             * //*/



            // ------------------------ page 172 - Properties and Indexers ------------------------

            /*
             * System.Console.WriteLine(Olli.Origin);
             * System.Console.WriteLine(Olli.Age);
             * try
             * {
             *  Olli.FavoritPrimaryColor = "yello";
             *
             * }
             * catch (Exception e)
             * {
             *  System.Console.WriteLine(e.Message);
             * }
             * System.Console.WriteLine(Olli.FavoritPrimaryColor);
             *
             * Olli.Children.Add(new Person("child1"));
             * Olli.Children.Add(new Person("child2"));
             * Olli.Children.Add(new Person("child3"));
             * System.Console.WriteLine(Olli.Children[4]);
             */



            // ------------------------ page 167 - parameter passing ------------------------

            /*
             * int a = 10;
             * int b = 20;
             * int c = 30;
             * System.Console.WriteLine($"Before: a = {a}, b = {b}, c = {c}");
             * Olli.PassingParameters(a, ref b, out c);
             * System.Console.WriteLine($"After: a = {a}, b = {b}, c = {c}");
             */



            // ------------------------ page 165 - method overloading ------------------------
            // System.Console.WriteLine(Olli.SayHello("Lena"));


            // ------------------------ page 162 - tuple / deconstruct tuple ------------------------
            (string, int)fruits = Olli.GetFruit();

            /*
             * System.Console.WriteLine($"There are {fruits.Item2} {fruits.Item1} ");
             * // Deconstruct tuple
             * (string fruit, int amount) = Olli.GetFruit();
             * System.Console.WriteLine($"{fruit}, {amount}");
             *
             * var fruitNamed = Olli.GetNamedFruit();
             * System.Console.WriteLine($"There are {fruitNamed.Numbers} {fruitNamed.Name}");
             */



            // ------------------------ page 158 - default ------------------------
            ThingOfDefaults defaultThing = new();
            //System.Console.WriteLine(defaultThing);



            // ------------------------ page 157 - constructor ------------------------
            Person Sigi = new("Sigi", new DateTime(2018, 09, 07));

            //System.Console.WriteLine(Sigi.ToString());



            // ------------------------ page 156 - const / read-only ------------------------
            //System.Console.WriteLine($"{Olli.Name} is a {Person.Species}");



            // ------------------------ page 155 - static ------------------------
            BankAccount.InterestRate = 0.012M;

            var lenasAccount = new BankAccount();

            lenasAccount.accountName = "Lenas Account";
            lenasAccount.Balance     = 5500;
            //System.Console.WriteLine(format: "{0} earned {1:C} interest.", arg0: lenasAccount.accountName, arg1: lenasAccount.Balance * BankAccount.InterestRate);



            // ------------------------ page 150 - basics ------------------------
            Person Lena = new();

            Lena.Name           = "Lena";
            Lena.favoriteWonder = WondersOfTheAncientWorld.LighthouseOfAlexandria;
            Lena.DateOfBirth    = new DateTime(1986, 09, 07);

            Person Sigggi = new Person {
                Name = "Sigi", DateOfBirth = new DateTime(2019, 12, 24), favoriteWonder = (WondersOfTheAncientWorld).3
            };

            Lena.Children.Add(new Person {
                Name = "child1"
            });
            Lena.Children.Add(new Person()
            {
                Name = "child2"
            });

            /*
             * Console.WriteLine(
             *  format: "{0} was born on {1:dddd, d MMMM yyyy} and likes {2} (int of wonder: ). ",
             *  arg0: Lena.name,
             *  arg1: Lena.dateOfBirth,
             *  arg2: Lena.favoriteWonder);
             *
             * Console.WriteLine(
             *  format: "{0} came to us on {1: dd MMM yy} and likes {2}",
             *  arg0: Sigi.name,
             *  arg1: Sigi.dateOfBirth,
             *  arg2: Sigi.favoriteWonder);
             *
             * foreach (var child in Lena.children) {
             *  System.Console.WriteLine(child.name);
             * }
             */
        }
    }