Inheritance: BaseClass
コード例 #1
0
        public void EndMemberAssignsInstanceToParentProperty()
        {
            var state = new StackingLinkedList<Level>();

            var dummyClass = new DummyClass();
            var xamlType = WiringContext.TypeContext.GetXamlType(dummyClass.GetType());
            state.Push(
                new Level
                {
                    Instance = dummyClass,
                    XamlMember = xamlType.GetMember("Child"),
                });

            var childClass = new ChildClass();
            state.Push(
                new Level
                {
                    XamlType = xamlType,
                    Instance = childClass,
                });

            var sut = new ObjectAssembler(state, WiringContext, new TopDownValueContext());

            sut.Process(X.EndObject());

            Assert.AreEqual(1, state.Count);
            var expectedInstance = state.CurrentValue.Instance;

            Assert.AreSame(expectedInstance, dummyClass);
            Assert.AreSame(((DummyClass)expectedInstance).Child, childClass);
        }
コード例 #2
0
            public RootClass()
                : base(MessageClass.Application)
            {
                Log.InitialStackMessages.ConcatenateWith("Class Date", DateTime.Now.ToLongDateString());

                using (Logger.AppendStackMessages(LogStackMessages.Empty.ConcatenateWith("Class Date", DateTime.Now.ToLongDateString())))
                {
                    A = new ChildClass("A");
                    B = new ChildClass("B");
                    C = new ChildClass("C");
                }
            }
コード例 #3
0
        public void TestDeserializationOfTwoBs() {
            var server = MongoServer.Create("mongodb://localhost/?safe=true");
            var database = server["onlinetests"];
            var collection = database["csharp100"];

            collection.RemoveAll();
            var obj = new ChildClass { SomeProperty = null };
            collection.Save(obj, SafeMode.True);
            obj = new ChildClass { SomeProperty = new List<SomeClass>() };
            collection.Save(obj, SafeMode.True);
            obj = new ChildClass { SomeProperty = new List<SomeClass> { new SomeClass() } };
            collection.Save(obj, SafeMode.True);
            obj = new ChildClass { SomeProperty = new List<SomeClass> { new SomeClass(), new SomeClass() } };
            collection.Save(obj, SafeMode.True);
            obj = new ChildClass { SomeProperty = new [] { new SomeClass(), new SomeClass() } };
            collection.Save(obj, SafeMode.True);
        }
コード例 #4
0
        public void ShallowCloneToObjectHierarchy()
        {
            var source      = new ParentClass();
            var sourceChild = new ChildClass {
                Name = "John Doe"
            };

            source.Child = sourceChild;

            var destination      = new ParentClass();
            var destinationChild = new ChildClass();

            destination.Child = destinationChild;

            Cloneable <ParentClass> .ShallowCloneTo(source, destination);

            Assert.IsTrue(object.ReferenceEquals(sourceChild, destination.Child));
        }
コード例 #5
0
ファイル: TestClass.cs プロジェクト: Roland0511/slua
        public void DictionaryClassKey()
        {
            var child = new ChildClass();
            var dict = new Dictionary<object, ulong>();
            dict[child] = 321;
            var code = @"
            function Func(dict, child)
            dict[child] = 888
            return dict[child]
            end
            return Func
            ";
            var ret = luaSvr.luaState.doString(code);
            var func = ret as LuaFunction;
            var result = func.call(dict, child);

            Assert.AreEqual(888, result);
        }
コード例 #6
0
ファイル: Program.cs プロジェクト: hwisnik/HWEnterpriseLogger
            //Note that loggInstance is injected as a dependency of Logit
            public void Logit(ILog loggingInstance)
            {
                EntLogger.LogDebug(loggingInstance, "Entering LogIt");
                try
                {
                    throw new Exception("Test Message Text", new Exception("Inner Exception Text"));
                }
                catch (Exception ex)
                {
                    EntLogger.LogException(loggingInstance, ex.Message, ex);
                }

                EntLogger.LogDebug(loggingInstance, "Exiting LogIt");

                ChildClass childClass = new ChildClass();

                childClass.LoggingFromChildClass(loggingInstance);
            }
コード例 #7
0
ファイル: CSharp100Tests.cs プロジェクト: RavenZZ/MDRelation
        public void TestDeserializationOfTwoBs()
        {
            var server = LegacyTestConfiguration.Server;
            var database = LegacyTestConfiguration.Database;
            var collection = LegacyTestConfiguration.Collection;

            collection.RemoveAll();
            var obj = new ChildClass { SomeProperty = null };
            collection.Save(obj);
            obj = new ChildClass { SomeProperty = new List<SomeClass>() };
            collection.Save(obj);
            obj = new ChildClass { SomeProperty = new List<SomeClass> { new SomeClass() } };
            collection.Save(obj);
            obj = new ChildClass { SomeProperty = new List<SomeClass> { new SomeClass(), new SomeClass() } };
            collection.Save(obj);
            obj = new ChildClass { SomeProperty = new[] { new SomeClass(), new SomeClass() } };
            collection.Save(obj);
        }
コード例 #8
0
        public void IgnoreISerializableCyclicReferenceLoop()
        {
            var main  = new MainClass();
            var child = new ChildClass();

            child.Name   = "Child1";
            child.Parent = main; // Obvious Circular Reference

            main.Child = child;

            var settings = new JsonSerializerSettings()
            {
                ReferenceLoopHandling = ReferenceLoopHandling.Ignore
            };

            var c = JsonConvert.SerializeObject(main, settings);

            Assert.AreEqual(@"{""Child"":{""Name"":""Child1""}}", c);
        }
コード例 #9
0
        public void DictionaryClassKey()
        {
            var child = new ChildClass();
            var dict  = new Dictionary <object, ulong>();

            dict[child] = 321;
            var code   = @"
function Func(dict, child)
    dict[child] = 888
    return dict[child]
end
return Func
";
            var ret    = LuaSvr.mainState.doString(code);
            var func   = ret as LuaFunction;
            var result = func.call(dict, child);

            Assert.AreEqual(888, result);
        }
コード例 #10
0
        public void GeneralInheritance()
        {
            var first = new ChildClass {
                Name = "Key"
            };
            var instance = new Container {
                First = first, Second = first
            };
            var container = new ConfigurationContainer();

            container.EnableReferences();
            var support = new SerializationSupport(container);
            var actual  = support.Cycle(instance);

            actual.First.Should()
            .NotBeNull()
            .And.BeOfType <ChildClass>()
            .And.BeSameAs(actual.Second);
        }
コード例 #11
0
        public void SetMemberValueShouldChangeFildValue()
        {
            // Given
            var baseInstance  = new BaseClass();
            var childInstance = new ChildClass();

            // Then
            Assert.IsTrue(baseInstance.SetMemberValue("BaseField", "BaseClass.NewBaseField") &&
                          Equals(baseInstance.BaseField, "BaseClass.NewBaseField"));
            Assert.IsTrue(baseInstance.SetMemberValue("BaseStaticField", "BaseClass.NewBaseStaticField") &&
                          Equals(BaseClass.BaseStaticField, "BaseClass.NewBaseStaticField"));
            Assert.IsTrue(childInstance.SetMemberValue("BaseField", "ChildClass.NewBaseField") &&
                          Equals(childInstance.BaseField, "ChildClass.NewBaseField"));
            Assert.IsTrue(childInstance.SetMemberValue("BaseStaticField", "ChildClass.NewBaseStaticField") &&
                          Equals(BaseClass.BaseStaticField, "ChildClass.NewBaseStaticField"));
            Assert.IsTrue(childInstance.SetMemberValue("ChildField", "ChildClass.NewChildField") &&
                          Equals(childInstance.ChildField, "ChildClass.NewChildField"));
            Assert.IsTrue(childInstance.SetMemberValue("ChildStaticField", "ChildClass.NewChildStaticField") &&
                          Equals(ChildClass.ChildStaticField, "ChildClass.NewChildStaticField"));
        }
コード例 #12
0
    private List <ChildClass> GetRepositary()
    {
        List <ChildClass> allChild = new List <ChildClass>();
        Random            r        = new Random();

        for (int i = 0; i < 50; i++)
        {
            ChildClass c = new ChildClass
            {
                ChildId  = i,
                ParentId = r.Next(5, 10),
                Name     = "Child Name " + i,
                Roll     = i
            };

            allChild.Add(c);
        }

        return(allChild);
    }
コード例 #13
0
        public void GetMemberValueShouldReturnFieldValue()
        {
            // Given
            var baseInstance  = new BaseClass();
            var childInstance = new ChildClass();

            // Then
            Assert.AreEqual(baseInstance.GetMemberValue("BaseField"), baseInstance.BaseField);
            Assert.AreEqual(baseInstance.GetMemberValue("BaseReadonlyField"), baseInstance.BaseReadonlyField);
            Assert.AreEqual(baseInstance.GetMemberValue("BaseStaticField"), BaseClass.BaseStaticField);
            Assert.AreEqual(baseInstance.GetMemberValue("BaseStaticReadonlyField"), BaseClass.BaseStaticReadonlyField);
            Assert.AreEqual(childInstance.GetMemberValue("BaseField"), childInstance.BaseField);
            Assert.AreEqual(childInstance.GetMemberValue("BaseReadonlyField"), childInstance.BaseReadonlyField);
            Assert.AreEqual(childInstance.GetMemberValue("BaseStaticField"), BaseClass.BaseStaticField);
            Assert.AreEqual(childInstance.GetMemberValue("BaseStaticReadonlyField"), BaseClass.BaseStaticReadonlyField);
            Assert.AreEqual(childInstance.GetMemberValue("ChildField"), childInstance.ChildField);
            Assert.AreEqual(childInstance.GetMemberValue("ChildReadonlyField"), childInstance.ChildReadonlyField);
            Assert.AreEqual(childInstance.GetMemberValue("ChildStaticField"), ChildClass.ChildStaticField);
            Assert.AreEqual(childInstance.GetMemberValue("ChildStaticReadonlyField"),
                            ChildClass.ChildStaticReadonlyField);
        }
コード例 #14
0
        public void SetMemberValueShouldChangeEventDelegate()
        {
            // Given
            var baseInstance = new BaseClass();

            baseInstance.BaseEvent    += () => "BaseClass.BaseEvent";
            baseInstance.VirtualEvent += () => "BaseClass.VirtualEvent";
            BaseClass.BaseStaticEvent += () => "BaseClass.BaseStaticEvent";
            var childInstance = new ChildClass();

            childInstance.BaseEvent     += () => "ChildClass.BaseEvent";
            childInstance.ChildEvent    += () => "ChildClass.ChildEvent";
            childInstance.VirtualEvent  += () => "ChildClass.VirtualEvent";
            ChildClass.ChildStaticEvent += () => "ChildClass.ChildStaticEvent";

            // Then
            Assert.IsTrue(baseInstance.SetMemberValue("BaseEvent", new Func <object>(() => "BaseClass.NewBaseEvent")) &&
                          Equals(baseInstance.InvokeBaseEvent(), "BaseClass.NewBaseEvent"));
            Assert.IsTrue(
                baseInstance.SetMemberValue("VirtualEvent", new Func <object>(() => "BaseClass.NewVirtualEvent")) &&
                Equals(baseInstance.InvokeVirtualEvent(), "BaseClass.NewVirtualEvent"));
            Assert.IsTrue(
                baseInstance.SetMemberValue("BaseStaticEvent", new Func <object>(() => "BaseClass.NewBaseStaticEvent")) &&
                Equals(BaseClass.InvokeBaseStaticEvent(), "BaseClass.NewBaseStaticEvent"));
            Assert.IsTrue(
                childInstance.SetMemberValue("BaseEvent", new Func <object>(() => "ChildClass.NewBaseEvent")) &&
                Equals(childInstance.InvokeBaseEvent(), "ChildClass.NewBaseEvent"));
            Assert.IsTrue(
                childInstance.SetMemberValue("ChildEvent", new Func <object>(() => "ChildClass.NewChildEvent")) &&
                Equals(childInstance.InvokeChildEvent(), "ChildClass.NewChildEvent"));
            Assert.IsTrue(
                childInstance.SetMemberValue("VirtualEvent", new Func <object>(() => "ChildClass.NewVirtualEvent")) &&
                Equals(childInstance.InvokeVirtualEvent(), "ChildClass.NewVirtualEvent"));
            Assert.IsTrue(
                childInstance.SetMemberValue("ChildStaticEvent",
                                             new Func <object>(() => "ChildClass.NewChildStaticEvent")) &&
                Equals(ChildClass.InvokeChildStaticEvent(), "ChildClass.NewChildStaticEvent"));
        }
コード例 #15
0
    public static void Main()
    {
        /*
         * PART 21: Inheritance
         * http://youtu.be/OLTk0xAVY00
         *
         * Inheritance syntax,
         * derived class : base class
         *
         * FOUR PILLARS OF OOP
         * 1. Inheritance
         * 2. Encapsulation
         * 3. Abstraction
         * 4. Polymorphism
         *
         * Each class can only have ONE base class
         * C# supports multiple interface inheritance
         * Base classes are automatically instantiated before inherited classes
         * Using base(), you can determine which constructor the child class will run
         *
         */

        FullTimeEmployee FTE = new FullTimeEmployee();

        FTE.firstName    = "Joe";
        FTE.lastName     = "Blowe";
        FTE.yearlySalary = 50000;
        FTE.printFullName();

        PartTimeEmployee PTE = new PartTimeEmployee();

        PTE.firstName  = "Joel";
        PTE.lastName   = "Blow";
        PTE.hourlyRate = 10;
        PTE.printFullName();

        ChildClass CC = new ChildClass();
    }
コード例 #16
0
ファイル: ChildService.cs プロジェクト: KyereAntwi/NGOProject
        public async Task <bool> UpdateClass(Guid classId, Guid childId)
        {
            var childClass = await _dataContext.ChildClasses.SingleOrDefaultAsync(c => c.ChildId == childId);

            if (childClass != null)
            {
                childClass.ClassId = classId;
                _dataContext.ChildClasses.Update(childClass);
            }
            else
            {
                ChildClass newOne = new ChildClass
                {
                    ChildId = childId,
                    ClassId = classId
                };

                await _dataContext.ChildClasses.AddAsync(newOne);
            }

            await _dataContext.SaveChangesAsync();

            return(true);
        }
コード例 #17
0
        static void Main(string[] args)
        {
            // Here is my example of arrays
            string[] names = new string[5] {
                "Ibrahim", "Michael", "Cesar", "Tyler", "Brennen"
            };
            foreach (string name in names)
            {
                Console.WriteLine($"{name}");
            }

            // Other Needed Code
            ChildClass child = new ChildClass();

            child.print();

            Console.WriteLine("Enter your number: ");
            double number = Convert.ToDouble(Console.ReadLine());
            int    count  = CountDivisions(number);

            Console.WriteLine($"Total number of divisions: {count}");
            Console.ReadKey();

            int first  = 0;
            int second = 0;

            Console.WriteLine("Enter your first number: ");
            first = System.Int32.Parse(Console.ReadLine());
            Console.WriteLine("Enter your second number: ");
            second = System.Int32.Parse(Console.ReadLine());
            int result = Divide(first, second);

            Console.WriteLine($"The result of dividing {first} by {second} is {result}");

            MyInformation.Ibrahim();
        }
コード例 #18
0
 public void AddChild(ChildClass child)
 {
     Children.Add(child);
     // or something else, etc.
 }
コード例 #19
0
ファイル: BaseClass.cs プロジェクト: JeremiahZhang/AKA
    public static void Main()
    {
        ChildClass child = new ChildClass();

        child.print();
    }
コード例 #20
0
        public void RecursiveObjectsTest()
        {
            var a = new TestClass();
            var b = new ChildClass();
            a.list.Add(a);
            a.list.Add(a);
            a.list.Add(b);
            a.list.Add(a);
            a.list.Add(b);
            b.list.Add(a);
            string yaml = serializer.Serialize(a);
            // %YAML 1.2
            // ---
            // &A !YamlSerializerTest.TestClass
            // list: 
            //   Capacity: 8
            //   ICollection.Items: 
            //     - *A
            //     - *A
            //     - &B !YamlSerializerTest.ChildClass
            //       list: 
            //         Capacity: 4
            //         ICollection.Items: 
            //           - *A
            //     - *A
            //     - *B
            // ...
            Assert.AreEqual(
                BuildResult(
                    "&A !YamlSerializerTest.TestClass",
                    "list: ",
                    "  Capacity: 8",
                    "  ICollection.Items: ",
                    "    - *A",
                    "    - *A",
                    "    - &B !YamlSerializerTest.ChildClass",
                    "      list: ",
                    "        Capacity: 4",
                    "        ICollection.Items: ",
                    "          - *A",
                    "    - *A",
                    "    - *B"
                    ),
                yaml);

            object restored = serializer.Deserialize(yaml)[0];
            Assert.AreSame(restored, ( (TestClass)restored ).list[0]);
            Assert.AreSame(restored, ( (TestClass)restored ).list[1]);
            Assert.AreSame(restored, ( (TestClass)restored ).list[2].list[0]);
            Assert.AreSame(restored, ( (TestClass)restored ).list[3]);
            Assert.AreSame(( (TestClass)restored ).list[2], ( (TestClass)restored ).list[4]);
            Assert.IsInstanceOf<ChildClass>(( (TestClass)restored ).list[2]);
        }
コード例 #21
0
        public static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");

            int  ls  = 927;
            byte shj = 255;

            Console.WriteLine("ls={0}", ls);
            Console.WriteLine("shj={0}", shj);

            int v1 = 0;
            int v2 = v1;

            v2 = 927;
            C r1 = new C();
            C r2 = r1;

            r2.Value = 112;
            Console.WriteLine("Values: {0},{1}", v1, v2);
            Console.WriteLine("Refs: {0},{1}", r1.Value, r2.Value);

            int k = (int)DateTime.Now.DayOfWeek;

            switch (k)
            {
            case (int)MyDate.Sun:
                Console.WriteLine("今天星期天");
                break;

            case (int)MyDate.Mon:
                Console.WriteLine("今天星期一");
                break;

            case (int)MyDate.Tue:
                Console.WriteLine("今天星期二");
                break;

            case (int)MyDate.Wed:
                Console.WriteLine("今天星期三");
                break;

            case (int)MyDate.Thi:
                Console.WriteLine("今天星期四");
                break;

            case (int)MyDate.Fri:
                Console.WriteLine("今天星期五");
                break;

            case (int)MyDate.Sat:
                Console.WriteLine("今天星期六");
                break;
            }

            double x = 1993545.0112;
            int    y = (int)x;

            Console.WriteLine(y);

            int z = Convert.ToInt32(y);

            Console.WriteLine(z);

            Object o = x;

            Console.WriteLine("1. x的值为{0}, 装箱之后的对象为{1}", x, o);
            o = 345.1234;
            Console.WriteLine("2. x的值为{0}, 装箱之后的对象为{1}", x, o);

            int xx = 12;
            int yy = 22;

            Console.WriteLine(Math.Sin(xx * xx + yy * yy));

            //Console.Write("请输入一个年份:");
            //String str = Console.ReadLine();
            //int year = Int32.Parse(str);
            //bool isLeapYear = ((year % 400 == 0) || (year % 4 == 0 && year % 100 != 0));
            //String yesOrNo = isLeapYear ? "是" : "不是";
            //Console.WriteLine("{0}年{1}闰年", year, yesOrNo);

            String[] ls2 = new string[2] {
                "1", "2"
            };
            Console.WriteLine(ls2[0]);

            Type myType = typeof(int);

            Console.WriteLine("类型:{0}", myType);

            String str1 = "string1111";
            String str2 = "testHelloWorld";

            Console.WriteLine(String.Compare(str1, str2));
            Console.WriteLine(str1.CompareTo(str2));

            DateTime dt   = DateTime.Now;
            String   strB = String.Format("{0:D}", dt);

            Console.WriteLine(strB);

            // PadLeft, PadRight
            String strPad = "*^___^*";
            String str12  = strPad.PadLeft(7, '(').PadRight(8, ')');

            Console.WriteLine(str12);

            // HashTable
            Hashtable hashtable = new Hashtable();

            hashtable.Add("id", "001");
            hashtable.Add("sex", "男");
            hashtable.Add("name", "张三");
            foreach (DictionaryEntry dicEntry in hashtable)
            {
                Console.WriteLine("\t" + dicEntry.Key + "\t" + dicEntry.Value);
            }
            Console.WriteLine(hashtable.ContainsKey("id"));

            Chapter8_9.Date date = new Chapter8_9.Date();
            date.Day = 12;
            Console.WriteLine(date.Day);

            StructTest structTest;

            structTest.width  = 2.4;
            structTest.height = 4.5;
            Console.WriteLine("area: " + structTest.Area());

            StructTest structTest2 = new StructTest(4.0, 4.0);

            Console.WriteLine("area2: " + structTest2.Area());

            // class
            ChildClass childClass = new ChildClass();
            ClassTest  classTest  = childClass;

            classTest.X = 12;
            classTest.Y = 23;
            Console.WriteLine(classTest.Add());
        }
 private void Log(ChildClass child)
 {
     Debug.Log("子类Log,对象 = " + child);
 }
コード例 #23
0
    public static void Main()
    {
        ChildClass child = new ChildClass();

        child.print();
    }
        protected override void Establish_context()
        {
            _spec = new MixinIsAbstractWithProtectedNonParameterlessConstructorSpec();

            _childClass = new ChildClass();
        }
コード例 #25
0
 public DeepClassReadonly()
 {
     Child = new ChildClass();
 }
コード例 #26
0
ファイル: Program.cs プロジェクト: sumit753/C-sharp
    {   //For Delegate Example.
        //we can get rid of this method by using lambda expression
        //public static bool promoteMethod(EmployeeClass emp)
        //{
        //    if (emp.expierence > 5)
        //    {
        //        return true;
        //    }
        //    else
        //        return false;

        //}



        static void Main(string[] args)
        {
            // ####### MethodHiding Code###########
            Console.WriteLine("############ MethodHiding ###");
            //this will call parent class method implementation
            ParentClass pObj = new ParentClass();

            pObj.printFullName();

            //this will call parent class method implementation
            ParentClass parentRef = new ChildClass();

            parentRef.printFullName();

            //this will call child class method implementation

            ChildClass cObj = new ChildClass();

            cObj.printFullName();

            //######## Method Code Ends##########


            //######## Runtime Polymorphism..
            // it allows to invoke derived class methods through base class reference during runtime.
            Console.WriteLine(" ");
            Console.WriteLine(" ");
            Console.WriteLine("############ Runtime PolyMorphism ###");
            Console.WriteLine(" ");
            Console.WriteLine(" ");

            // creating the array of Employee reference
            Employee[] empRef = new Employee[4];

            empRef[0] = new Employee();
            empRef[1] = new PartTimeEmployee();
            empRef[2] = new FullTimeEmployee();
            empRef[3] = new TemporaryEmployee();

            foreach (Employee e in empRef)
            {
                e.display();
            }

            Console.WriteLine(" ");

            // properties Example
            Console.WriteLine("############ Properties Example ###");
            Console.WriteLine(" ");
            PropertyExample Student = new PropertyExample();

            Student.Id    = 10;
            Student.Name  = "Sumit";
            Student.Email = "*****@*****.**";
            Student.City  = "Indore";

            Console.WriteLine("Student Details");

            Console.WriteLine("ID- " + Student.Id + " Name : " + Student.Name + " Email: " + Student.Email + " City : " + Student.City);
            Console.WriteLine(" ");

            Console.WriteLine("===== Explict InterfaceExample==== ");
            Console.WriteLine(" ");

            InterfaceExample iObj = new InterfaceExample();

            // defult implementation will be called i.e. I1's method implementation
            iObj.InterfaceMethod();

            //Interface I2's  method will be called
            ((I2)iObj).InterfaceMethod();

            // Or we can do following

            I2 i2_ref = new InterfaceExample();

            i2_ref.InterfaceMethod();


            //Interface I3's  method will be called
            ((I3)iObj).InterfaceMethod();

            // OR
            I3 i3_ref = new InterfaceExample();

            i3_ref.InterfaceMethod();

            Console.WriteLine(" ");

            Console.WriteLine("===== Multiple Inheritance Through Interfaces ==== ");
            Console.WriteLine(" ");

            AB abObj = new AB();

            abObj.methodA();
            abObj.methodB();


            Console.WriteLine(" ");

            Console.WriteLine("===== Delegate Example ==== ");
            Console.WriteLine(" ");

            Console.WriteLine("Promoted Employeees ");

            List <EmployeeClass> empList = new List <EmployeeClass>();

            empList.Add(new EmployeeClass()
            {
                id = 1, name = "Laxman", salary = 15000, expierence = 6
            });
            empList.Add(new EmployeeClass()
            {
                id = 2, name = "Ramesh", salary = 68400, expierence = 7
            });
            empList.Add(new EmployeeClass()
            {
                id = 3, name = "Rahil", salary = 7000, expierence = 3
            });

            //no need to intialize the delegate now
            //isPromotable isPromotableDelegate = new isPromotable(promoteMethod);

            //using lambda expression
            // "empLambdaExpName" will be automaticaly associate itself with "EmployeeClass" which is passed in Declaration of Delegate.
            EmployeeClass.promoteEmployee(empList, empLambdaExpName => empLambdaExpName.expierence > 2);

            Console.WriteLine(" ");

            Console.WriteLine("===== Anonymous Method Demo ==== ");
            Console.WriteLine(" ");

            List <Person> personList = new List <Person>();

            personList.Add(new Person()
            {
                Name = "Sumit", Age = 24
            });
            personList.Add(new Person()
            {
                Name = "Amit", Age = 25
            });
            personList.Add(new Person()
            {
                Name = "Aman", Age = 18
            });
            personList.Add(new Person()
            {
                Name = "Chinky", Age = 20
            });
            personList.Add(new Person()
            {
                Name = "Pinky", Age = 19
            });

            //Step 2 Anonymous method example -create instance of Predicate<Person> delegate and
            // pass the name of method created in step 1 into Perdicate's constructor.

            Predicate <Person> personDelgate = new Predicate <Person>(Person.criteriaMethod);

            //Step 3 Anonymous method example
            //Now pass the delegate instance as an argument for Find method.

            Person p = personList.Find(person => personDelgate(person));

            Console.WriteLine("====Without Using Anonymous Method===");
            Console.WriteLine(" ");
            Console.WriteLine(p.Name);
            //we did all these three steps because Find() method accepts Predicate delegate as an agrument.
            // find method return only first occurance of matched condition in the entire list. If we need all
            // occurences than we can use FindAll() method.

            Console.WriteLine("");
            Console.WriteLine("====Using Anonymous Method===");
            Console.WriteLine("");
            //Anonymous method is passed as and argument in Find method
            // This anonymous method replace the need for step 1,2 &3

            Person person1 = personList.Find(

                //anonymous method
                delegate(Person x)
            {
                return(x.Age < 20);
            }


                );

            Console.WriteLine(person1.Name);

            Console.WriteLine("");
            // Console.WriteLine("====Using Atrribute Demo===");
            //Console.WriteLine("");

            //AttributeExample objAttribute = new AttributeExample();
            //its showing warning when we are using add method.
            //objAttribute.Add(10, 20);

            Console.WriteLine("");
            Console.WriteLine("==== Generics Demo===");
            Console.WriteLine("");

            GenericsDemo genDemo = new GenericsDemo();
            bool         result  = genDemo.compareVariables <int>(10, 20);

            Console.WriteLine("are 10 & 20 equal?? :" + result);

            bool result2 = genDemo.compareVariables <string>("Sumit", "Karma");

            Console.WriteLine("are Sumit & karma equal ?? :" + result2);

            Console.WriteLine("");
            Console.WriteLine("====Dictionary Demo===");
            Console.WriteLine("");

            Dictionary <int, EmployeeClass> employeeDictionary = new Dictionary <int, EmployeeClass>();

            EmployeeClass emp1 = new EmployeeClass()
            {
                id = 1, name = "Sumit", salary = 10000
            };
            EmployeeClass empl2 = new EmployeeClass()
            {
                id = 2, name = "Amit", salary = 5000
            };
            EmployeeClass emp3 = new EmployeeClass()
            {
                id = 3, name = "Rahul", salary = 4850
            };

            employeeDictionary.Add(emp1.id, emp1);
            employeeDictionary.Add(empl2.id, empl2);
            employeeDictionary.Add(emp3.id, emp3);

            //accessing the dictionary using key
            EmployeeClass emp = employeeDictionary[1];

            Console.WriteLine(emp);

            Console.WriteLine();
            //Understanding dictionary methods
            EmployeeClass emp4 = new EmployeeClass()
            {
                id = 4, name = "Vaibhav", salary = 15000
            };
            EmployeeClass emp5 = new EmployeeClass()
            {
                id = 5, name = "Ranu", salary = 5100
            };
            EmployeeClass emp6 = new EmployeeClass()
            {
                id = 6, name = "Rakesh", salary = 14850
            };

            EmployeeClass[] empArray = new EmployeeClass[3];
            empArray[0] = emp4;
            empArray[1] = emp5;
            empArray[2] = emp6;

            //converting array into Dictionary

            Dictionary <int, EmployeeClass> empDict = empArray.ToDictionary(y => y.id, y => y);

            employeeDictionary.AddRange(empDict);
            Console.WriteLine("---------After Merging two dictionary-----------------------");
            foreach (KeyValuePair <int, EmployeeClass> keyvaluepair in employeeDictionary)
            {
                EmployeeClass eRef = keyvaluepair.Value;
                Console.WriteLine(eRef);
                Console.WriteLine("---------------------------------------------");
            }

            Console.WriteLine("Dictionary Count Function");

            int i = employeeDictionary.Count(ep => ep.Value.salary > 14000);

            Console.WriteLine(i);


            Console.WriteLine("");
            Console.WriteLine("====Sorting Complex types Demo===");
            Console.WriteLine("");


            //using the EmployeeClass list created at line no 128
            Console.WriteLine("-------------------------");
            Console.WriteLine("EmployeeList Before Sorting");
            Console.WriteLine("-------------------------");
            foreach (EmployeeClass empl in empList)
            {
                Console.WriteLine("Name : {0} , Salary{1}", empl.name, empl.salary);
            }
            empList.Sort();
            Console.WriteLine(" ");
            Console.WriteLine("-------------------------");
            Console.WriteLine("EmployeeList after Sorting");
            Console.WriteLine("-------------------------");
            foreach (EmployeeClass empl in empList)
            {
                Console.WriteLine("Name : {0} , Salary : {1}", empl.name, empl.salary);
            }

            //we can also sort empList by name,salary,id By creating another class and implementing
            // IComparer interface. & then creating the object of that class and passing it in Sort method
            // as argument.
            Console.WriteLine(" ");
            Console.WriteLine("-------------------------");
            Console.WriteLine("EmployeeList Sorting by name");
            Console.WriteLine("-------------------------");
            Console.WriteLine(" ");
            EmployeeSortByNameClass EmpByName = new EmployeeSortByNameClass();

            empList.Sort(EmpByName);
            foreach (EmployeeClass empl in empList)
            {
                Console.WriteLine("Name : {0} , Salary : {1}", empl.name, empl.salary);
            }
            Console.WriteLine(" ");
            Console.WriteLine("-------------------------");
            Console.WriteLine("EmployeeList Sorting by salary");
            Console.WriteLine("-------------------------");
            Console.WriteLine(" ");
            EmployeeSortBySalaryClass EmpBySalary = new EmployeeSortBySalaryClass();

            empList.Sort(EmpBySalary);
            foreach (EmployeeClass empl in empList)
            {
                Console.WriteLine("Name : {0} , Salary : {1}", empl.name, empl.salary);
            }

            // Console.ReadKey();
        }
コード例 #27
0
 void Method()
 {
     ChildClass cc  = new ChildClass();
     string     str = cc.Name;
     // cc will have the same name as the cc in MainClass
 }
コード例 #28
0
 static void Main(string[] args)
 {
     var name = new ChildClass();
 }
コード例 #29
0
ファイル: Perf.Linq.cs プロジェクト: noahfalk/corefx
 public void Cast_ToBaseClass(int size, int iteration, Perf_LinqTestBase.WrapperType wrapType)
 {
     Func<IEnumerable<ChildClass>, IEnumerable<BaseClass>> linqApply = col => col.Cast<BaseClass>();
     ChildClass val = new ChildClass() { Value = 1, ChildValue = 2 };
     Perf_LinqTestBase.Measure<ChildClass, BaseClass>(10, 5, val, wrapType, linqApply);
 }
コード例 #30
0
ファイル: TestClass.cs プロジェクト: alpull/ITB1701
            public static void Main(string[] args)
            {
                // Class inheritance: Exercise 5
                DebitCard dCard = new DebitCard("debit");

                dCard.SetBalance(800);
                dCard.MakePayment(900); // Can't make this payment
                dCard.MakePayment(700);
                dCard.PrintCardInfo();
                dCard.CloseCard();
                dCard.PrintCardInfo();

                CreditCard cCard = new CreditCard("credit", -500);

                cCard.OpenCard();
                cCard.MakePayment(600); // Can't make this payment
                cCard.MakePayment(400);
                cCard.CloseCard();
                cCard.PrintCardInfo();

                // Class inheritance: Exercise 4
                Shape[] shapes = new Shape[3];
                shapes[0] = new Circle();
                shapes[1] = new Square();
                shapes[2] = new Triangle();

                foreach (Shape shape in shapes)
                {
                    shape.Draw();
                }

                List <Shape> shapeList = new List <Shape>();

                shapeList.Add(new Circle());
                shapeList.Add(new Square());
                shapeList.Add(new Triangle());

                foreach (Shape shape in shapeList)
                {
                    shape.Draw();
                }

                // Class inheritance: Exercise 2
                ChildClass myChild = new ChildClass();

                myChild.print();

                ParentClass parent = new ParentClass();

                parent.print();

                // Interface
                Dog myDog = new Dog();

                myDog.Travel("space");
                myDog.Eat("a carrot");

                Rabbit myRabbit = new Rabbit();

                myRabbit.Travel("Tartu");
                myRabbit.Eat("a horse");

                Console.ReadLine();
            }
コード例 #31
0
        public static void PrintTrueOrFalseFromChildClass()
        {
            ChildClass childClass = new ChildClass();

            childClass.PrintTrueOrFalse(true);
        }
コード例 #32
0
    static void Main()
    {
        BaseClass bc = new ChildClass();

        bc.PrintMethod();
    }
コード例 #33
0
    /*
     * Section 6.13.1 Function Overrides
     *
     * Instantiate a Parent of the ParentClass object.
     *
     */

    private void Start()
    {
        {
            /*
             * Example 6.13.1.1 A Basic Example.
             *
             * Instantiation happens here.
             */

            ParentClass parent = new ParentClass();
            parent.ParentFunction();

            /*           ↑
             * Parent calls on it's function call.
             *           │
             *         ╭─────────────╮
             *         │ ParentClass │
             *         ╰──┬──────────╯
             *            │
             *            ╰───→ParentFunction()┐
             *                    │            │
             *                    ├→FunctionA()┤
             *                    ╰→FunctionB()┴→────┐
             *         ╭────────────╮                ↓
             *         │ ChildClass │           ╔════╧═════════════════╗
             *         ╰──┬─────────╯           ║ChildClass            ║
             *            │                     ║calls the parent's    ║
             *            ╰→ChildFunction()     ║version of FunctionB()║
             *            ┊  │                  ╚════╤═════════════════╝
             *            ┊  ╰→ParentFunction()┐     ↓
             *            ┊       │            │     │
             *            ┊       ├→FunctionA()┤     ↓
             *            ┊       ╰→FunctionB()┴←────┘
             *            ┊  //child class
             *            ╰┈┈┈┈┈┈┈┈new FunctionB()
             *                      │
             *            ┌─────────┴──────────────────┐
             *            │new hides the parent version│
             *            │of the FunctionB() this     │
             *            │version of FunctionB() isn't│
             *            │called by ChildFunction()   │
             *            └────────────────────────────┘
             *
             *           however when we use override the following happens.
             *
             *         ╭────────────╮                     ↓
             *         │ ChildClass │                ╔════╧═════════════════╗
             *         ╰──┬─────────╯                ║ChildClass            ║
             *            │                          ║calls the parent's    ║
             *            ╰─→ChildFunction()         ║version of FunctionB()║
             *            ┊   │                      ╚════╤═════════════════╝
             *            ┊   ╰→ParentFunction()┐         ↓
             *            ┊        │            │         │
             *            ┊        ├→FunctionB()┴←────────┘
             *            ┊╭──────←┴←virtual FunctionA()
             *            ┊│             │            ╔═════════════════════════════╗
             *            ┊↓             └────────────╢ virtual tells FunctionA()   ║
             *            ┊│                          ║ to change what the Parent   ║
             *            ┊↓  //child class           ║ version does if an override ║
             *            ┊╰→ override FunctionA()    ║ version is present in the   ║
             *            ╰┈┈┈┈┈┈┈┈new FunctionB()    ║ child class but is called   ║
             *                                        ║ when the parent version     ║
             *                                        ║ is called.                  ║
             *                                        ╚═════════════════════════════╝
             */
            ChildClass child = new ChildClass();
            child.ChildFunction();

            /*         ↑                             *
            * The child calls the ChildFunction()   *
            * which skips the child's version of    *
            * FunctionB() but does use the child    *
            * version of FunctionA since it's using *
            * override                              */
        }
        {
            /*
             * Section 6.13.2 Class Inheritance
             */
            ZombieClass  zombie  = new ZombieClass();
            VampireClass vampire = new VampireClass();
            // zombie.HitPoints = 10;
            // vampire.HitPoints = 10;

            /* Assignment of HitPoints = 10
             * every time might be redundant.
             * so they've been added to the
             * constructor of BaseMonsterClass
             */
            Debug.Log(zombie.TakeDamage(5));
            Debug.Log(vampire.TakeDamage(5));
        }
        {
            ZombieClass zombie = new ZombieClass();

            /*
             * Section 6.13.3 Object
             * After adding an override
             * for the ToString() function
             * in zombie we can get a custom
             * Debug.Log() function from it.
             */
            Debug.Log(zombie);
            // "I'm a Zombie!"
        }
    }
コード例 #34
0
 public static void DoExtension(this ChildClass bar)
 {
 }
コード例 #35
0
        public void ShallowCloneToObjectHierarchyWithNullDestinationChild()
        {
            var source = new ParentClass();
            var sourceChild = new ChildClass { Name = "John Doe" };

            source.Child = sourceChild;

            var destination = new ParentClass();

            Cloneable<ParentClass>.ShallowCloneTo(source, destination);

            Assert.IsTrue(object.ReferenceEquals(sourceChild, destination.Child));
            Assert.AreEqual(sourceChild.Name, destination.Child.Name);
        }
コード例 #36
0
 static void Main()
 {
     ChildClass c = new ChildClass();
 }
コード例 #37
0
 protected override void BecauseOf()
 {
     result = Sut.Deserialize<ChildClass>(SampleXml);
 }
コード例 #38
0
 static void Main(string[] args)
 {
     //AbstracteBaseClass abc = new AbstracteBaseClass()
     ChildClass cc = new ChildClass();
     Console.WriteLine(cc.AbtractMethos(123);
 }
コード例 #39
0
 public RootClass(ChildClass child)
 {
     Child = child;
 }
 public void Sample()
 {
     ChildClass cd = new ChildClass();
     int a = 4;
     cd.Func(a);
     cd.Funct(new C());
 }
コード例 #41
0
    public void Children()
    {
        var p = new ChildClass();

        StaticClass.SomeMethod(p);
    }
コード例 #42
0
ファイル: Program.cs プロジェクト: dearz/Practice
        //继承相关测试
        public static void TestInherit()
        {
            BaseClass a = new BaseClass();
            BaseClass b = new ChildClass();
            ChildClass c = new ChildClass();
            a.Show();
            b.Show();
            c.Show();
            a.Show2();
            b.Show2();
            c.Show2();
            a.Show3();
            b.Show3();
            c.Show3();

            Console.WriteLine("------------");
            int counter = 100;
            while ((counter--) > 0)
            {
                b.Show3();
            }
        }
コード例 #43
0
 static void Main(string[] args)
 {
     var child = new ChildClass("Viktor", "Jakovlev", 31);
 }
コード例 #44
0
 public NonEmptyConstructor(string test, int test2, ChildClass childClass)
 {
     Test = test;
     Test2 = test2;
     ChildClass = childClass;
 }