Пример #1
0
        public void TestPersonStruct1()
        {
            PersonStruct person = new PersonStruct();

            person.Age             = 0;
            person.Name            = "";
            person.MetersTravelled = 0;

            ValueTypeHolder h      = person;
            Type            type   = person.GetType();
            MultiSetter     setter = Reflect.MultiSetter(type, "name", "totalPeopleCreated", "Age", "MetersTravelled");
            FieldInfo       field  = type.GetField("totalPeopleCreated", BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.GetField);

            setter(h, "Jack Black", 15, 5, 2.0d);
            person = (PersonStruct)h;
            Assert.IsTrue(person.Name == "Jack Black" && person.Age == 5 && person.MetersTravelled == 2 && ((int)field.GetValue(null) == 15));
        }
Пример #2
0
        public ActionResult GetPeopleJson()
        {
            var people = new List <PersonStruct>();

            foreach (var person in _db.Persons.AsEnumerable())
            {
                var user = new PersonStruct
                {
                    FullName    = person.FullName,
                    AccountName = person.AccountName,
                    Email       = person.Email,
                    Department  = person.Dep.Name
                };
                int.TryParse(person.PhoneNumber, out user.PhoneNumber);
                people.Add(user);
            }
            return(Json(people, JsonRequestBehavior.AllowGet));
        }
        public static void RunTest()
        {
            DateTime start, end;

            Console.WriteLine("# Starting 'Class' performance test...");
            start = DateTime.Now;
            for (int i = 0; i < 100000000; i++)
            {
                PersonClass person = new PersonClass()
                {
                    FirstName = "Nickolas",
                    LastName  = "Gupton",
                    Age       = 22
                };
            }
            end = DateTime.Now;
            Console.WriteLine("# Done. For 100,000,000 iterations it took: " + Utils.GetFormattedDuration(start, end));
            Console.WriteLine();


            Console.WriteLine("# Starting 'Struct' performance test...");
            start = DateTime.Now;
            for (int i = 0; i < 100000000; i++)
            {
                PersonStruct person = new PersonStruct()
                {
                    FirstName = "Nickolas",
                    LastName  = "Gupton",
                    Age       = 22
                };
            }
            end = DateTime.Now;
            Console.WriteLine("# Done. For 100,000,000 iterations it took: " + Utils.GetFormattedDuration(start, end));

            Console.WriteLine();
            Console.WriteLine("In C# it is a common design practice to hold multiple pieces \n"
                              + "of data in a single container Class that has no methods \n"
                              + "associated with it. These can be changed to use a Struct \n"
                              + "in order to gain additional performance from your \n"
                              + "application. Classes have additional overhead associated \n"
                              + "with their creation that Structs do not, which leads to a \n"
                              + "performance difference between the two.");
        }
        public void Equals_SecondPersonHasIncompatibleType_ReturnsFalse()
        {
            // Arrange
            var p1 = new PersonStruct
            {
                FirstName = "Kim",
                LastName  = "Kuan"
            };
            var p2 = new PersonClass
            {
                FirstName = "Kim",
                LastName  = "Kuan"
            };

            // Act
            var result = p1.Equals(p2);

            // Assert
            Assert.IsFalse(result);
        }
        public void Equals_LastNamesNotEqual_ReturnsFalse()
        {
            // Arrange
            var p1 = new PersonStruct
            {
                FirstName = "Kim",
                LastName  = "Kuan"
            };
            var p2 = new PersonStruct
            {
                FirstName = "Kim",
                LastName  = "Kuann"
            };

            // Act
            var result = p1.Equals(p2);

            // Assert
            Assert.IsFalse(result);
        }
        static void Main(string[] args)
        {
            // Create a normal struct
            var jane = new PersonStruct()
            {
                Name = "Jane", Age = 100
            };
            // Create a ref struct
            var bob = new PersonRefStruct()
            {
                Name = "Bob", Age = 100
            };

            // Since a struct is a value type, it can be boxed
            jane.GetHashCode();
            jane.ToString();

            // But a ref struct does not alow boxing, so these cause a compler error
            //bob.GetHashCode();
            //bob.ToString();
        }
        public void GetHashCode_LastNamesNotEqual_NotEqual()
        {
            // Arrange
            var p1 = new PersonStruct
            {
                FirstName = "Kim",
                LastName  = "Kuan"
            };
            var p2 = new PersonStruct
            {
                FirstName = "Kim",
                LastName  = "Kuann"
            };

            // Act
            var hash1 = p1.GetHashCode();
            var hash2 = p2.GetHashCode();

            // Assert
            Assert.AreNotEqual(hash1, hash2);
        }
Пример #8
0
        public void CSharpPersonStructTests()
        {
            // Arrange
            var person1 = new PersonStruct("Name", new DateTime(2000, 1, 1));
            var person2 = new PersonStruct("Name", new DateTime(2000, 1, 1));

            // Debug
            //output.WriteLine($"person1.GetHashCode(): {person1.GetHashCode()}");
            //output.WriteLine($"person2.GetHashCode(): {person2.GetHashCode()}");

            // Assert
            person1.Should().NotBeNull();
            person2.Should().NotBeNull();
            person1.Should().NotBeSameAs(person2);
            person1.Should().BeEquivalentTo(person2);

            person1.Name.Should().NotBeNullOrEmpty();
            person1.DateOfBirth.Should().HaveYear(2000);
            person1.Children.Should().NotBeNull();

            Assert.Equal(person1.GetHashCode(), person2.GetHashCode());
            Assert.Equal(person1, person2);
        }
Пример #9
0
 static string TestPassByStruct(PersonStruct p)
 {
     return(p.Name + p.Age + p.Credit);
 }
Пример #10
0
        public static void Main(string[] args)
        {
            // Index and Ranges
            Console.ForegroundColor = ConsoleColor.Cyan;
            Console.WriteLine("Index and Ranges");
            IndexRangesBefore80();
            Index();
            Ranges();
            IndexAndRanges();
            RangesWithStrings();
            RangesWithClasses();
            PrintSeparators();

            // Static Local Functions
            Console.ForegroundColor = ConsoleColor.Cyan;
            Console.WriteLine("Static Local Functions");
            var response = LocalFunctionBefore80();

            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine(response);
            response = StaticLocalFunction();
            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine(response);
            PrintSeparators();

            // Using Declarations
            Console.ForegroundColor = ConsoleColor.Cyan;
            Console.WriteLine("Using Declarations");
            Console.ForegroundColor = ConsoleColor.Green;
            ReadFile();
            PrintSeparators();

            // Default Interface Members
            Console.ForegroundColor = ConsoleColor.Cyan;
            Console.WriteLine("Default Interface Members");
            Console.ForegroundColor = ConsoleColor.Green;
            DefaultInterfaceMembers();
            PrintSeparators();

            // Readonly Members
            Console.ForegroundColor = ConsoleColor.Cyan;
            Console.WriteLine("Readonly Members");
            Console.ForegroundColor = ConsoleColor.Green;
            var personStruct = new PersonStruct("Peter", 29);

            personStruct.Age = 31;
            Console.WriteLine(personStruct.GetPerson());
            PrintSeparators();

            // Pattern Matching - Switch Expressions
            Console.ForegroundColor = ConsoleColor.Cyan;
            Console.WriteLine("Pattern Matching - Switch Expressions");
            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine(GetSwitchExpressions("Peter"));
            Console.WriteLine(GetSwitchExpressions("Mary"));
            Console.WriteLine(GetSwitchExpressions("Other"));
            Console.WriteLine(GetSwitchExpressions());
            PrintSeparators();

            // Pattern Matching - Property Patterns
            Console.ForegroundColor = ConsoleColor.Cyan;
            Console.WriteLine("Pattern Matching - Property Patterns");
            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine($"Discount for John with Id 1: {PatternMatchingPropertyPatterns(new Person() { IdDiscount = 1, Name = "John" }) * 100}%");
            Console.WriteLine($"Discount for Rose with Id 2: {PatternMatchingPropertyPatterns(new Person() { IdDiscount = 2, Name = "Rose" }) * 100}%");
            Console.WriteLine($"Discount for Mary with Id 3: {PatternMatchingPropertyPatterns(new Person() { IdDiscount = 3, Name = "Mary" }) * 100}%");
            try
            {
                Console.WriteLine($"null as {PatternMatchingPropertyPatterns(null)}%");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            PrintSeparators();

            // Pattern Matching - Tuple Patterns
            Console.ForegroundColor = ConsoleColor.Cyan;
            Console.WriteLine("Pattern Matching - Tuple Patterns");
            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine($"12 Celsius to Fahrenheit: {PatternMatchingTuplePatterns(Temperature.Celsius, Temperature.Fahrenheit, 12)}");
            Console.WriteLine($"57 Fahrenheit to Celsius: {PatternMatchingTuplePatterns(Temperature.Fahrenheit, Temperature.Celsius, 57)}");
            Console.WriteLine($"12 Celsius to Celsius: {PatternMatchingTuplePatterns(Temperature.Celsius, Temperature.Celsius, 12)}");
            Console.WriteLine($"57 Fahrenheit to Fahrenheit: {PatternMatchingTuplePatterns(Temperature.Fahrenheit, Temperature.Fahrenheit, 57)}");
            PrintSeparators();

            // Pattern Matching - Positional Patterns
            Console.ForegroundColor = ConsoleColor.Cyan;
            Console.WriteLine("Pattern Matching - Positional Patterns");
            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine($"John with 10: {PatternMatchingPositionalPatterns(new Student() { Name = "John", Grade = 10 })}");
            Console.WriteLine($"Mary with 10: {PatternMatchingPositionalPatterns(new Student() { Name = "Mary", Grade = 10 })}");
            Console.WriteLine($"Mary with 0: {PatternMatchingPositionalPatterns(new Student() { Name = "Mary", Grade = 0 })}");
            Console.WriteLine($"Mike with 0: {PatternMatchingPositionalPatterns(new Student() { Name = "Mike", Grade = 0 })}");
            Console.WriteLine($"Anne with 1: {PatternMatchingPositionalPatterns(new Student() { Name = "Anne", Grade = 1 })}");
            Console.WriteLine($"null as: {PatternMatchingPositionalPatterns(null)}");
            PrintSeparators();

            // Disposable red structs
            Console.ForegroundColor = ConsoleColor.Cyan;
            Console.WriteLine("Disposable red structs");
            Console.ForegroundColor = ConsoleColor.Magenta;
            Console.WriteLine($"Without special code => see the {nameof(MyStruct)} struct to see this");
            Console.WriteLine($"Adding {nameof(MyStruct.Dispose)} the struct will be disposable");
            PrintSeparators();

            // Asynchronous Streams
            Console.ForegroundColor = ConsoleColor.Cyan;
            Console.WriteLine("Asynchronous Streams");
            Console.ForegroundColor = ConsoleColor.Green;
            // This is not a good practice
            UseTraditionalAsyncStreamsAsync().Wait();
            // New feature
            UseAsyncStreamsAsync().Wait();
            PrintSeparators();

            // Null coalescing assignment
            Console.ForegroundColor = ConsoleColor.Cyan;
            Console.WriteLine("Null coalescing assignment");
            Console.ForegroundColor = ConsoleColor.Magenta;
            Console.WriteLine($"Without special code => see the {nameof(NullCoalescingAssignment)} method for more details");
            Console.ForegroundColor = ConsoleColor.Green;
            NullCoalescingAssignment();
            PrintSeparators();

            // Nullable reference types
            Console.ForegroundColor = ConsoleColor.Cyan;
            Console.WriteLine("Nullable reference types");
            Console.ForegroundColor = ConsoleColor.Magenta;
            Console.WriteLine($"Without special code => see the {nameof(NullableReferenceTypes)} method and the csproj");
            NullableReferenceTypes();
            PrintSeparators();

            Console.ResetColor();
            Console.WriteLine();
            Console.WriteLine("Press any key to close");
            Console.ReadKey();
        }
Пример #11
0
 /// <summary>Рассчитывает сколько осталось до идеального индекса массы.</summary>
 /// <param name="person">Структура человека с необходимыми данными</param>
 /// <param name="greatIndexMass">Индекс к которому стремимся</param>
 /// <returns></returns>
 public static double GetMassFromGreatIndex(PersonStruct person, double greatIndexMass)
 {
     return(greatIndexMass * (person.height / 100) * (person.height / 100));
 }
Пример #12
0
 /// <summary>Рассчитывает индекс массы человека.</summary>
 /// <param name="person">Структура человека с необходимыми данными</param>
 /// <returns></returns>
 public static double GetIndexMass(PersonStruct person)
 {
     return(person.weight / ((person.height / 100) * (person.height / 100)));
 }
Пример #13
0
        private async void ButtonRegStart_OnClick(object sender, RoutedEventArgs e)
        {
            if (Utils.PersonsList.Count < 1)
            {
                return;
            }

            ButtonIsEnable(false);
            Utils.CaptchaLife     = 120;
            Utils.MaxCaptchaQueue = 10;
            Utils.IsPermit        = true;
            Utils.AntigateService = "rucaptcha.com";
            CaptchaTimer.Elapsed += RaiseOnTimerElapsed;
            CaptchaTimer.Start();
            Utils.ResultPers = new List <PersonStruct>();

            var list = Utils.PersonsList;

            await Task.Run(async() =>
            {
                while (list.Count > 0 && Utils.IsPermit)
                {
                    var current = new PersonStruct();
                    try
                    {
                        while (Utils.CaptchaQueueCount < 1 && Utils.IsPermit)
                        {
                            await Task.Delay(1000);
                        }

                        if (!Utils.IsPermit)
                        {
                            break;
                        }

                        current = list[0];
                        Utils.PersonsList.Remove(current);

                        var result = await MainCycle.GetResult(list[0], Utils.CaptchaQueue);

                        if (result == "Compleate")
                        {
                            Informer.RaiseOnResultReceived($"Account for {list[0].Mail} successfully registered");
                            current.Result = "registered but not confirmed";
                        }
                        else
                        {
                            throw new Exception(result);
                        }
                    }
                    catch (Exception ex)
                    {
                        if (ex.Message.Contains("There is already"))
                        {
                            current.Result = "confirmed";
                        }
                        else if (ex.Message.Contains("Не удалось соединиться с HTTP-сервером"))
                        {
                            current.Result = "proxy fail";
                        }
                        else
                        {
                            current.Result = "fail register";
                        }
                        Informer.RaiseOnResultReceived(ex.Message.Contains("Не удалось соединиться с HTTP-сервером")
                            ? $"Bad proxy {current.Proxy.Host} for {current.Mail}"
                            : $"{ex.Message} for {current.Mail}");
                    }
                    Utils.ResultPers.Add(current);
                }

                //CaptchaTimer.Stop();
                //CaptchaTimer.Elapsed -= RaiseOnTimerElapsed;

                await XlsxSave.SaveInXls(Utils.ResultPers, "ResultReg.xlsx");
                await XlsxSave.SaveInXls(list, "RestReg.xlsx");

                Utils.DisposeWebDrivers();
            });

            ButtonIsEnable(true);
        }
 static void AddAge(PersonStruct person)
 {
     person.Age += 10;
 }
Пример #15
0
        static void Main(string[] args)
        {
            int loopSize = 10000000;

            Benchmark(() =>
            {
                var p = new Person()
                {
                    Name   = "code6421",
                    Age    = 12,
                    Credit = 120000
                };
                for (var i = 0; i < loopSize; i++)
                {
                    TestPassByClass(p);
                }
            }, "By Class");

            Benchmark(() =>
            {
                var p = new PersonStruct()
                {
                    Name   = "code6421",
                    Age    = 12,
                    Credit = 120000
                };
                for (var i = 0; i < loopSize; i++)
                {
                    TestPassByStruct(p);
                }
            }, "By Struct");

            Benchmark(() =>
            {
                var p = new Person()
                {
                    Name   = "code6421",
                    Age    = 12,
                    Credit = 120000
                };
                for (var i = 0; i < loopSize; i++)
                {
                    TestPassByClass(p);
                }
            }, "By Class");

            Benchmark(() =>
            {
                var p = new PersonStruct()
                {
                    Name   = "code6421",
                    Age    = 12,
                    Credit = 120000
                };
                for (var i = 0; i < loopSize; i++)
                {
                    TestPassByStruct(p);
                }
            }, "By Struct");

            Benchmark(() =>
            {
                var p = new Person()
                {
                    Name   = "code6421",
                    Age    = 12,
                    Credit = 120000
                };
                for (var i = 0; i < loopSize; i++)
                {
                    TestPassByClass(p);
                }
            }, "By Class");

            Benchmark(() =>
            {
                var p = new PersonStruct()
                {
                    Name   = "code6421",
                    Age    = 12,
                    Credit = 120000
                };
                for (var i = 0; i < loopSize; i++)
                {
                    TestPassByStruct(p);
                }
            }, "By Struct");

            Console.ReadLine();
        }
Пример #16
0
 private PersonStruct StructPass(PersonStruct person)
 {
     return(person);
 }
Пример #17
0
        static void Main(string[] args)
        {
            {
                PersonStruct p1;
                //p1.Id++;
                p1.Id      = 2;
                p1.ErILive = true;

                PersonStruct p2 = new PersonStruct(); // Brug det der new for at sikre at der er intialiseret
                p2.Id++;
                p2.Id      = 2;
                p2.ErILive = true;

                System.Console.WriteLine(p1.Id);
                System.Console.WriteLine(p2.Id);

                p1    = p2; // kopierer værdier IKKE reference
                p2.Id = 5;

                System.Console.WriteLine(p1.Id);
                System.Console.WriteLine(p2.Id);

                // De fleste vil lave en klassse ikke en struct
                // Der hvor man gerne vil kopiere værdier er det bedre at bruge structs
                // struct er en mindre sammensat type

                System.Console.WriteLine();

                PersonClass p3;
                p3         = new PersonClass();
                p3.Id      = 3;
                p3.ErILive = true;
                //System.Console.WriteLine(p3.Id);

                PersonClass p4 = new PersonClass();
                p4.Id      = 4;
                p4.ErILive = false;

                System.Console.WriteLine(p3.Id);
                System.Console.WriteLine(p4.Id);

                p3 = p4; // så peger p3 reference nu på samme memory som p4
                System.Console.WriteLine(p3.Id);
                System.Console.WriteLine(p4.Id);
            }

            {
                System.Console.WriteLine();
                System.Console.WriteLine();

                int[] i;
                i = new int[5];

                int[] x = new int[5];

                x[0] = 2;
                //x[0] = "dsfdsf"; NEJ!!!
                x[1] = 3;
                x[3] = 76;
                //x[8] = 22; NEJ!!!!!

                System.Console.WriteLine(x[0]);

                System.Console.WriteLine(x);

                for (int r = 0; r < x.Length; r++)
                {
                    System.Console.WriteLine(x[r]);
                }

                System.Console.WriteLine();
                System.Console.WriteLine();

                int[] xx = { 2, 5, 0, 76, 0 };
            }


            {
                int[] j = { 5, 3, 74 };
                int[] x = { 7, 8, 1, 6, 5, 4 };

                System.Console.WriteLine(j[1]);
                System.Console.WriteLine(x[1]);
                System.Console.WriteLine(j == x);
                j = x; // Nu er de ens

                System.Console.WriteLine(j[1]);
                System.Console.WriteLine(x[1]);
                System.Console.WriteLine(j == x);


                System.Array.Sort(x);

                System.Console.WriteLine();
                System.Console.WriteLine(x.Length);
            }



            if (System.Diagnostics.Debugger.IsAttached)
            {
                System.Console.Write("Press any key to continue . . . ");
                System.Console.ReadKey();
            }
        }