Inheritance: Interface
            public void WillIgnoreReadOnlyFields()
            {
                var instance = new DerivedClass();
                var map = ObjectMapper.GetState(instance);

                Assert.False(map.ContainsKey("ReadOnlyField"));
            }
            public void WillMapNonPublicFields()
            {
                var instance = new DerivedClass();
                var map = ObjectMapper.GetState(instance);

                Assert.Equal("PrivateField", map["PrivateField"]);
            }
            public void WillMapNonPublicProperties()
            {
                var instance = new DerivedClass();
                var map = ObjectMapper.GetState(instance);

                Assert.Equal("PrivateAutoProperty", map["PrivateAutoProperty"]);
            }
            public void WillIgnorePropertiesMarkedWithIgnoreAttribute()
            {
                var instance = new DerivedClass();
                var map = ObjectMapper.GetState(instance);

                Assert.False(map.ContainsKey("IgnoredProperty"));
            }
Example #5
0
    public static void Main()
    {
        // Check raw type GetHashCode
        int i1 = 0;
        object i2 = 0;
        System.Console.WriteLine(i1.GetHashCode() == i2.GetHashCode()  ? "true" : "false");

        // Check type with several base.GetHashCode
        var c1 = new DerivedClass();
        object c2 = new DerivedClass();

        System.Console.WriteLine(c1.GetHashCode() == c2.GetHashCode() ? "true" : "false");
        System.Console.WriteLine(c1.GetHashCode() == c1.GetHashCode() ? "true" : "false");
        System.Console.WriteLine(c2.GetHashCode() == c2.GetHashCode() ? "true" : "false");

        // Equals
        System.Console.WriteLine(i1.Equals(i2) ? "true" : "false");
        System.Console.WriteLine(i2.Equals(i1) ? "true" : "false");
        System.Console.WriteLine(i1.Equals(i1) ? "true" : "false");
        System.Console.WriteLine(i2.Equals(i2) ? "true" : "false");

        System.Console.WriteLine(c1.Equals(c2) ? "true" : "false");
        System.Console.WriteLine(c2.Equals(c1) ? "true" : "false");
        System.Console.WriteLine(c1.Equals(c1) ? "true" : "false");
        System.Console.WriteLine(c2.Equals(c2) ? "true" : "false");
    }
    public static void Main() {

        BaseClass obj1=new BaseClass();
        CheckReturnedInt(obj1.F1("obj1"), 1);
        CheckReturnedString(obj1.F2("obj1"), "String returned from BaseClass.F2:obj1");
        CheckReturnedString(obj1.NonVirtualFunc(11), "String returned from BaseClass.NonVirtualFunc:11");
        Console.WriteLine("");

        DerivedClass obj2=new DerivedClass();
        CheckReturnedInt(obj2.F1("obj2"), 2);
        CheckReturnedString(obj2.F2("obj2"), "String returned from DerivedClass.F2:obj2");
        CheckReturnedString(obj2.NonVirtualFunc(15), "String returned from DerivedClass.NonVirtualFunc:30");
        Console.WriteLine("");

        BaseClass objectRef;
        objectRef = obj1;
        CheckReturnedInt(objectRef.F1("objectRef is now obj1"), 1);
        CheckReturnedString(objectRef.F2("objectRef is now obj1"), "String returned from BaseClass.F2:objectRef is now obj1");
        CheckReturnedString(objectRef.NonVirtualFunc(11), "String returned from BaseClass.NonVirtualFunc:11");
        Console.WriteLine("");

        objectRef = obj2;
        CheckReturnedInt(objectRef.F1("objectRef is now obj2"), 2);
        CheckReturnedString(objectRef.F2("objectRef is now obj2"), "String returned from DerivedClass.F2:objectRef is now obj2");
        CheckReturnedString(objectRef.NonVirtualFunc(15), "String returned from BaseClass.NonVirtualFunc:15");
        Console.WriteLine("");

        if (failed) {
             System.Environment.ExitCode = 1;
        }
        else {
             System.Environment.ExitCode = 0;
        }
        
    }
            public void IgnoresBaseClassPropertyLambda()
            {
                var source = new DerivedClass();
                var settings = PropertiesSettings.Build()
                                                 .IgnoreProperty<ComplexType>(x => x.Excluded)
                                                 .CreateSettings(ReferenceHandling.Structural);

                var propertyChanges = new List<string>();
                var changes = new List<EventArgs>();
                using (var tracker = Track.Changes(source, settings))
                {
                    tracker.PropertyChanged += (_, e) => propertyChanges.Add(e.PropertyName);
                    tracker.Changed += (_, e) => changes.Add(e);
                    Assert.AreEqual(0, tracker.Changes);
                    CollectionAssert.IsEmpty(propertyChanges);
                    CollectionAssert.IsEmpty(changes);

                    source.Value++;
                    Assert.AreEqual(1, tracker.Changes);
                    CollectionAssert.AreEqual(new[] { "Changes" }, propertyChanges);
                    var expected = new[] { RootChangeEventArgs.Create(ChangeTrackerNode.GetOrCreate(source, tracker.Settings, false).Value, new PropertyChangeEventArgs(source, source.GetProperty(nameof(source.Value)))) };
                    CollectionAssert.AreEqual(expected, changes, EventArgsComparer.Default);

                    source.Excluded++;
                    Assert.AreEqual(1, tracker.Changes);
                    CollectionAssert.AreEqual(new[] { "Changes" }, propertyChanges);
                    CollectionAssert.AreEqual(expected, changes, EventArgsComparer.Default);
                }
            }
Example #8
0
	public static int Main(string[] args)
	{
		DerivedClass o = new DerivedClass();

		Func<string> del1 = GetDel1 (o);
		Func<string> del2 = GetDel2 (o);


		Console.WriteLine("Action\n======\nReflected type: {0}\nDeclaring type: {1}\nAttributes: {2}\nResult: {3}",
			del1.Method.ReflectedType, del1.Method.DeclaringType, del1.Method.Attributes, del1 ());

		Console.WriteLine ();

		Console.WriteLine("Delegate\n========\nReflected type: {0}\nDeclaring type: {1}\nAttributes: {2}\nResult: {3}",
			del2.Method.ReflectedType, del2.Method.DeclaringType, del2.Method.Attributes, del2 ());

		if (del1.Method.ReflectedType != typeof (DerivedClass))
			return 10;
		if (del1.Method.DeclaringType != typeof (DerivedClass))
			return 11;
		if (del1 () != "Derived method")
			return 12;

		if (del2.Method.ReflectedType != typeof (DerivedClass))
			return 20;
		if (del2.Method.DeclaringType != typeof (DerivedClass))
			return 21;
		if (del2 () != "Derived method")
			return 22;

		return 0;
	}
    static void Main()
    {
        DerivedClass dc = new DerivedClass();
        BaseClass bc = dc;

        bc.VirtualMethod();
        bc.NonVirtualMethod();
    }
Example #10
0
        public void TestCloneOfAbstractClass()
        {
            BaseClass obj1 = new DerivedClass();

            var clone = obj1.DeepCloneWithoutSerialization();

            var clone2 = obj1.DeepCloneWithSerialization();
        }
    public static void Main (string[] args) {
        var a = new DerivedClass();
        var b = new DerivedClass2();

        a.Method1();
        a.Method2();
        b.Method1();
        b.Method2();
    }
Example #12
0
        public void Should_invoke_consume_contravariantly()
        {
            var consumer = Substitute.For<IConsumer<BaseClass>>();

            var message = new DerivedClass();
            consumer.InvokePreservingStackTrace(message);

            consumer.Received().Consume(message);
        }
        public void GetClone_InterfaceInitializerSpecified_InstanceCloned()
        {
            IInterface source = new DerivedClass() { InterfaceProperty = 10};
            var initializers = new Dictionary<Type, Func<object, object>>() {
                { typeof(IInterface), (s) => new DerivedClass() }
            };
            var target = CloneFactory.GetClone(source, initializers);

            Assert.AreNotSame(source, target);
            Assert.AreEqual(source.InterfaceProperty, target.InterfaceProperty);
        }
Example #14
0
        public void GetTypeHierarchyTest()
        {
            object o = new DerivedClass();
            string expected = "BaseClass-DerivedClass";
            string actual = string.Join("-", PluginsContainerAccessor<object>.Access_GetTypeHierarchy(o.GetType()).Select(type => type.Name));
            Assert.AreEqual(expected, actual);

            o = new object();
            expected = "";
            actual = string.Join("-", PluginsContainerAccessor<object>.Access_GetTypeHierarchy(o.GetType()).Select(type => type.Name));
            Assert.AreEqual(expected, actual);
        }
        public void DefaultName()
        {
            /*DerivedClass test = new DerivedClass();
             *
             * If an instance of the DerivedClass object is created line(23)
             * Intellisense will only provide the methods, objects
             * declared in this class (QuadripleInput())
            */

            BaseClass test = new DerivedClass();
            Assert.AreEqual("derived default", test.Name);
        }
Example #16
0
        public void GetTypeHierarchyTest()
        {
            object o = new DerivedClass();
            string expected = "BaseClass-DerivedClass";
            string actual = string.Join("-", CsUtility.GetClassHierarchy(o.GetType()).Select(type => type.Name));
            Assert.AreEqual(expected, actual);

            o = new object();
            expected = "";
            actual = string.Join("-", CsUtility.GetClassHierarchy(o.GetType()).Select(type => type.Name));
            Assert.AreEqual(expected, actual);
        }
        public void Casts_to_derived_type()
        {
            var expected = new DerivedClass();

            var result = (IEnumerable)ResolveResultFactory.CreateResult(
                typeof(IResolve<DerivedClass>).GetTypeInfo(),
                new BaseClass[] { expected },
                Mock.Of<IResolveBuilder>(),
                Enumerable.Empty<ResolveFailure>()
            );

            Assert.IsType(typeof(ResolveResult<DerivedClass>), result);

            var actual = Assert.Single(result);
            Assert.Same(expected, actual);
        }
Example #18
0
        public void GetPropertyExplorer_ReturnsNull_ForPropertyNotFound()
        {
            // Arrange
            var model = new DerivedClass()
            {
                Base1 = 5,
            };

            var provider = new EmptyModelMetadataProvider();
            var modelExplorer = provider.GetModelExplorerForType(typeof(BaseClass), model);

            // Act
            var propertyExplorer = modelExplorer.GetExplorerForProperty("BadName");

            // Assert
            Assert.Null(propertyExplorer);
        }
    static void Main()
    {
        BaseClass b1 = new BaseClass();
            DerivedClass d1 = new DerivedClass();

            b1.Name = "Mary";
            d1.Name = "John";

            b1.Id = "Mary123";
            d1.Id = "John123";  // The BaseClass.Id property is called.

            System.Console.WriteLine("Base: {0}, {1}", b1.Name, b1.Id);
            System.Console.WriteLine("Derived: {0}, {1}", d1.Name, d1.Id);

            // Keep the console window open in debug mode.
            System.Console.WriteLine("Press any key to exit.");
            System.Console.ReadKey();
    }
  private static int InvokeOveriddenMethods1() {

    // Return values 20 - 23
    int ret = 0;
    DerivedClass derivedClass = new DerivedClass();
    BaseClass baseClass = derivedClass;
    ret = baseClass.F();
    if (ret != 1)
      return 20;
    ret = derivedClass.F();
    if (ret != 3)
      return 21;
    ret = baseClass.G();
    if (ret != 4)
      return 22;
    ret = derivedClass.G();
    if (ret != 4)
      return 23;
    return 0;
  }
Example #21
0
 public static void Main()
 {
     BaseClass B = new DerivedClass();
     B.Print();
     //show the add f(x)
     Overloading.Add(2, 3);
     //show the overloaded add f(x)
     Overloading.Add(2.3F, 3.4F);
     //create a customer
     Customer C1 = new Customer("Tony", "Wittinger");
     C1.PrintFullName();
     //show the use of 'this'
     Circle Cir = new Circle(5);
     float Area = Cir.CalculateArea();
     Console.WriteLine("Area = {0}\n", Area);
     //Show the struct feature
     Student S1 = new Student(234, "Tony");
     S1.PrintDetails();
     
 }
    public static void OverVirtualHidelColl2()
    {
        BaseClass bc = new BaseClass();
            DerivedClass dc = new DerivedClass();
            BaseClass bcdc = new DerivedClass();

            bc.Method1();
            bc.Method2();
            dc.Method1();
            dc.Method2();
            bcdc.Method1();
            bcdc.Method2();

            // Output:
            // Base - Method1
            // Base - Method2
            // Derived - Method1
            // Derived - Method2
            // Derived - Method1
            // Base - Method2
    }
Example #23
0
        public void GetPropertyExplorer_DeferredModelAccess()
        {
            // Arrange
            var model = new DerivedClass()
            {
                Base1 = 5,
            };

            var provider = new EmptyModelMetadataProvider();
            var modelExplorer = provider.GetModelExplorerForType(typeof(BaseClass), model);

            // Change the model value after creating the explorer
            var propertyExplorer = modelExplorer.GetExplorerForProperty("Base1");
            model.Base1 = 17;

            // Act
            var propertyValue = propertyExplorer.Model;

            // Assert
            Assert.Equal(17, propertyValue);
        }
Example #24
0
        static void Main()
        {
            BaseClass b = new BaseClass();
            DerivedClass d = new DerivedClass();

            // Display custom attributes for each class.
            Console.WriteLine("Attributes on Base Class:");
            object[] attrs = b.GetType().GetCustomAttributes(true);
            foreach (Attribute attr in attrs)
            {
                Console.WriteLine(attr);
            }

            Console.WriteLine("Attributes on Derived Class:");
            attrs = d.GetType().GetCustomAttributes(true);
            foreach (Attribute attr in attrs)
            {
                Console.WriteLine(attr);
            }
            Console.ReadKey();
        }
Example #25
0
        //</snippet14>

        static void Main(string[] args)
        {
            //<snippet1>
            var currentPerformanceCounterCategory = new System.Diagnostics.
                                                    PerformanceCounterCategory();
            //</snippet1>

            int val1 = 1;
            int val2 = 2;
            int val3 = 3;

            //<snippet2>
            if ((val1 > val2) && (val1 > val3))
            {
                // Take appropriate action.
            }
            //</snippet2>

            //<snippet3>
            // The following declaration creates a query. It does not run
            // the query.
            //</snippet3>

            // Save snippet 4 and 5 for possible additions in program structure.

            Name[] nameList = { new Name {
                                    FirstName = "Anderson", LastName = "Redmond"
                                },
                                new Name {
                                    FirstName = "Jones", LastName = "Seattle"
                                },
                                new Name {
                                    FirstName = "Anderson", LastName = "Redmond"
                                } };
            int    n = 0;

            //<snippet6>
            string displayName = $"{nameList[n].LastName}, {nameList[n].FirstName}";

            //</snippet6>

            Console.WriteLine("{0}, {1}", nameList[n].LastName, nameList[n].FirstName);
            Console.WriteLine(nameList[n].LastName + ", " + nameList[n].FirstName);

            //<snippet7>
            var phrase      = "lalalalalalalalalalalalalalalalalalalalalalalalalalalalalala";
            var manyPhrases = new StringBuilder();

            for (var i = 0; i < 10000; i++)
            {
                manyPhrases.Append(phrase);
            }
            //Console.WriteLine("tra" + manyPhrases);
            //</snippet7>

            //<snippet8>
            // When the type of a variable is clear from the context, use var
            // in the declaration.
            var var1 = "This is clearly a string.";
            var var2 = 27;
            //</snippet8>

            //<snippet9>
            // When the type of a variable is not clear from the context, use an
            // explicit type. You generally don't assume the type clear from a method name.
            // A variable type is considered clear if it's a new operator or an explicit cast.
            int var3 = Convert.ToInt32(Console.ReadLine());
            int var4 = ExampleClass.ResultSoFar();
            //</snippet9>

            //<snippet10>
            // Naming the following variable inputInt is misleading.
            // It is a string.
            var inputInt = Console.ReadLine();

            Console.WriteLine(inputInt);
            //</snippet10>

            //<snippet11>
            var syllable = "ha";
            var laugh    = "";

            for (var i = 0; i < 10; i++)
            {
                laugh += syllable;
                Console.WriteLine(laugh);
            }
            //</snippet11>

            //<snippet12>
            foreach (char ch in laugh)
            {
                if (ch == 'h')
                {
                    Console.Write("H");
                }
                else
                {
                    Console.Write(ch);
                }
            }
            Console.WriteLine();
            //</snippet12>

            //<snippet13>
            // Preferred syntax. Note that you cannot use var here instead of string[].
            string[] vowels1 = { "a", "e", "i", "o", "u" };

            // If you use explicit instantiation, you can use var.
            var vowels2 = new string[] { "a", "e", "i", "o", "u" };

            // If you specify an array size, you must initialize the elements one at a time.
            var vowels3 = new string[5];

            vowels3[0] = "a";
            vowels3[1] = "e";
            // And so on.
            //</snippet13>

            //<snippet15>
            // In the Main method, create an instance of Del.

            // Preferred: Create an instance of Del by using condensed syntax.
            Del exampleDel2 = DelMethod;

            // The following declaration uses the full syntax.
            Del exampleDel1 = new Del(DelMethod);

            //</snippet15>

            exampleDel1("Hey");
            exampleDel2(" hey");

            // #16 is below Main.
            Console.WriteLine(GetValueFromArray(vowels1, 1));

            // 17 requires System.Drawing
            //<snippet17>
            // This try-finally statement only calls Dispose in the finally block.
            Font font1 = new Font("Arial", 10.0f);

            try
            {
                byte charset = font1.GdiCharSet;
            }
            finally
            {
                if (font1 != null)
                {
                    ((IDisposable)font1).Dispose();
                }
            }

            // You can do the same thing with a using statement.
            using (Font font2 = new Font("Arial", 10.0f))
            {
                byte charset = font2.GdiCharSet;
            }
            //</snippet17>

            //<snippet18>
            Console.Write("Enter a dividend: ");
            var dividend = Convert.ToInt32(Console.ReadLine());

            Console.Write("Enter a divisor: ");
            var divisor = Convert.ToInt32(Console.ReadLine());

            // If the divisor is 0, the second clause in the following condition
            // causes a run-time error. The && operator short circuits when the
            // first expression is false. That is, it does not evaluate the
            // second expression. The & operator evaluates both, and causes
            // a run-time error when divisor is 0.
            if ((divisor != 0) && (dividend / divisor > 0))
            {
                Console.WriteLine("Quotient: {0}", dividend / divisor);
            }
            else
            {
                Console.WriteLine("Attempted division by 0 ends up here.");
            }
            //</snippet18>

            //<snippet19>
            var instance1 = new ExampleClass();
            //</snippet19>

            //<snippet20>
            ExampleClass instance2 = new ExampleClass();
            //</snippet20>

            //<snippet21>
            // Object initializer.
            var instance3 = new ExampleClass {
                Name     = "Desktop", ID = 37414,
                Location = "Redmond", Age = 2.3
            };

            // Default constructor and assignment statements.
            var instance4 = new ExampleClass();

            instance4.Name     = "Desktop";
            instance4.ID       = 37414;
            instance4.Location = "Redmond";
            instance4.Age      = 2.3;
            //</snippet21>

            // #22 and #23 are in Coding_Conventions_WF, below.

            // Save 24 in case we add an exxample to Static Members.

            ExampleClass.totalInstances = 1;

            var customers = new List <Customer>
            {
                new Customer {
                    Name = "Jones", ID = 432, City = "Redmond"
                }
            };

            // Check shop name to use this.
            var distributors = new List <Distributor>
            {
                new Distributor {
                    Name = "ShopSmart", ID = 11302, City = "Redmond"
                }
            };

            //<snippet25>
            //<snippet28>
            var seattleCustomers = from customer in customers
                                   //</snippet28>
                                   where customer.City == "Seattle"
                                   select customer.Name;
            //</snippet25>

            //<snippet26>
            var localDistributors =
                from customer in customers
                join distributor in distributors on customer.City equals distributor.City
                select new { Customer = customer, Distributor = distributor };
            //</snippet26>

            //<snippet27>
            var localDistributors2 =
                from customer in customers
                join distributor in distributors on customer.City equals distributor.City
                select new { CustomerName = customer.Name, DistributorID = distributor.ID };
            //</snippet27>

            //<snippet29>
            var seattleCustomers2 = from customer in customers
                                    where customer.City == "Seattle"
                                    orderby customer.Name
                                    select customer;
            //</snippet29>

            // #30 is in class CompoundFrom

            var customerDistributorNames =
                from customer in customers
                join distributor in distributors on customer.City equals distributor.City
                select new { CustomerName = customer.Name, DistributorID = distributor.ID };

            var customerDistributorNames2 =
                from customer in customers
                from distributor in distributors
                where customer.City == distributor.City
                select new { CustomerName = customer.Name, DistributorID = distributor.ID };

            foreach (var c in customerDistributorNames)
            {
                Console.WriteLine(c);
            }

            // Could use in Static Members.
            Console.WriteLine(BaseClass.IncrementTotal());
            // Do not do access the static member of the base class through
            // a derived class.
            Console.WriteLine(DerivedClass.IncrementTotal());

            //// Error
            //var instance = new ExampleClass();
            //Console.WriteLine(instance.IncrementTotal());
        }
 public void GetClone_InterfaceInitializerNotSpecified_InvalidOperationExceptionThrown()
 {
     IInterface source = new DerivedClass() { InterfaceProperty = 10 };
     var target = CloneFactory.GetClone(source);
 }
 public void createInstance()
 {
     DerivedClass p = new DerivedClass("test");
 }
Example #28
0
 public T CastToTypeParameter <T>(DerivedClass d) where T : BaseClass
 {
     return((T)(BaseClass)d);
 }
 static void Main()
 {
     DerivedClass md  = new DerivedClass();
     DerivedClass md1 = new DerivedClass(1);
 }
    public static void Main()
    {
        DerivedClass ob = new DerivedClass(1, 2);

        ob.show();
    }
Example #31
0
        public void PropertyHelper_ForDerivedClass()
        {
            // Arrange
            var derived = new DerivedClass { PropA = "propAValue", PropB = "propBValue" };

            // Act
            var helpers = PropertyHelper.GetProperties(derived).ToArray();

            // Assert
            Assert.NotNull(helpers);
            Assert.Equal(2, helpers.Length);

            var propAHelper = Assert.Single(helpers.Where(h => h.Name == "PropA"));
            var propBHelper = Assert.Single(helpers.Where(h => h.Name == "PropB"));

            Assert.Equal("propAValue", propAHelper.GetValue(derived));
            Assert.Equal("propBValue", propBHelper.GetValue(derived));
        }
        public BaseClass GetInheritingType()
        {
            var inheritance = new DerivedClass();

            return(inheritance);
        }
Example #33
0
 static void Main()
 {
     BaseClass    instance1 = new BaseClass();
     DerivedClass instance2 = new DerivedClass();
 }
 public void TestGenerate_NewPropertyInGenericDerivedClass_UsesDerivedProperty()
 {
     FormatCompiler compiler = new FormatCompiler();
     const string format = @"Hello, {{Value}}!!!";
     Generator generator = compiler.Compile(format);
     DerivedClass<string> instance = new DerivedClass<string>() { Value = "Derived" };
     string result = generator.Render(instance);
     Assert.AreEqual("Hello, Derived!!!", result, "The wrong text was generated.");
 }
Example #35
0
 public override void Write(DerivedClass data)
 {
     Console.printLn(data.Name);
     base.Write(data)
 }
    public void Delete()
    {
        DerivedClass dc = new DerivedClass();

        dc.DeletePerson(Guid.NewGuid());
    }
Example #37
0
        static void Main(string[] args)
        {
            // 示例一
            BaseClass    b = new BaseClass();
            DerivedClass d = new DerivedClass();

            // 查看类上的 特性
            // Display custom attributes for each class.
            Console.WriteLine("Attributes on Base Class:");
            object[] attrs = b.GetType().GetCustomAttributes(true);
            foreach (Attribute attr in attrs)
            {
                Console.WriteLine(attr);
            }

            Console.WriteLine("Attributes on Derived Class:");
            attrs = d.GetType().GetCustomAttributes(true);
            foreach (Attribute attr in attrs)
            {
                Console.WriteLine(attr);
            }

            // 示例2
            // 读取添加的特性的信息
            GetAttributeInfoByReflectionTest.Test();

            // 示例3
            // 获取 Student类上的特性
            var type = typeof(Student);

            if (type.IsDefined(typeof(CustomAttribute), true))
            {
                CustomAttribute attribute = type.GetCustomAttribute <CustomAttribute>();

                Console.WriteLine($"{attribute.Description} {attribute.Remark}");
            }
            // 获取属性上的特性
            PropertyInfo propertyInfo = type.GetProperty("Id");

            if (propertyInfo.IsDefined(typeof(CustomAttribute), true))
            {
                CustomAttribute attribute = propertyInfo.GetCustomAttribute <CustomAttribute>();

                Console.WriteLine($"{attribute.Description} {attribute.Remark}");
            }
            // 获取方法上的特性
            MethodInfo methodInfo = type.GetMethod("Answer");

            if (methodInfo.IsDefined(typeof(CustomAttribute), true))
            {
                CustomAttribute attribute = methodInfo.GetCustomAttribute <CustomAttribute>();

                Console.WriteLine($"{attribute.Description} {attribute.Remark}");
            }

            // 获取方法参数上的特性
            ParameterInfo parameterInfo = methodInfo.GetParameters()[0];

            if (parameterInfo.IsDefined(typeof(CustomAttribute), true))
            {
                CustomAttribute attribute = parameterInfo.GetCustomAttribute <CustomAttribute>();

                Console.WriteLine($"{attribute.Description} {attribute.Remark}");
            }

            // 获取返回值 上的 特性
            ParameterInfo returnParameterInfo = methodInfo.ReturnParameter;

            if (returnParameterInfo.IsDefined(typeof(CustomAttribute), true))
            {
                CustomAttribute attribute = returnParameterInfo.GetCustomAttribute <CustomAttribute>();

                Console.WriteLine($"{attribute.Description} {attribute.Remark}");
            }


            // 获取枚举值 前端显示名称
            {
                Console.WriteLine(UserState.Normal.GetRemark());
                Console.WriteLine(UserState.Frozen.GetRemark());
                Console.WriteLine(UserState.Deleted.GetRemark());
                Console.WriteLine(RemarkExtension.GetRemark(UserState.Deleted));
            }

            // 使用 特性 进行 数据合法性校验
            {
                var student1 = new Student()
                {
                    QQ = 5
                };
                var student2 = new Student()
                {
                    QQ = 6
                };
                Console.WriteLine(student1.QQ.Validate());
                Console.WriteLine(student2.QQ.Validate());
            }
        }
Example #38
0
		static void Main()
		{
			DerivedClass mdc = new DerivedClass();
			mdc.PrintMe();
		}
Example #39
0
        static void Main()
        {
            DerivedClass mdc = new DerivedClass();

            mdc.PrintMe();
        }
 public static string myFunc(DerivedClass dc)
 {
     return("DerivedClass");
 }
Example #41
0
        //</snippet14b>

        static void Main(string[] args)
        {
            //<snippet1>
            var currentPerformanceCounterCategory = new System.Diagnostics.
                                                    PerformanceCounterCategory();
            //</snippet1>

            int val1 = 1;
            int val2 = 2;
            int val3 = 3;

            //<snippet2>
            if ((val1 > val2) && (val1 > val3))
            {
                // Take appropriate action.
            }
            //</snippet2>

            //<snippet3>
            // The following declaration creates a query. It does not run
            // the query.
            //</snippet3>

            // Save snippet 4 and 5 for possible additions in program structure.

            Name[] nameList = { new Name {
                                    FirstName = "Anderson", LastName = "Redmond"
                                },
                                new Name {
                                    FirstName = "Jones", LastName = "Seattle"
                                },
                                new Name {
                                    FirstName = "Anderson", LastName = "Redmond"
                                } };
            int    n = 0;

            //<snippet6>
            string displayName = $"{nameList[n].LastName}, {nameList[n].FirstName}";

            //</snippet6>

            Console.WriteLine("{0}, {1}", nameList[n].LastName, nameList[n].FirstName);
            Console.WriteLine(nameList[n].LastName + ", " + nameList[n].FirstName);

            //<snippet7>
            var phrase      = "lalalalalalalalalalalalalalalalalalalalalalalalalalalalalala";
            var manyPhrases = new StringBuilder();

            for (var i = 0; i < 10000; i++)
            {
                manyPhrases.Append(phrase);
            }
            //Console.WriteLine("tra" + manyPhrases);
            //</snippet7>

            //<snippet8>
            var var1 = "This is clearly a string.";
            var var2 = 27;
            //</snippet8>

            //<snippet9>
            int var3 = Convert.ToInt32(Console.ReadLine());
            int var4 = ExampleClass.ResultSoFar();
            //</snippet9>

            //<snippet10>
            var inputInt = Console.ReadLine();

            Console.WriteLine(inputInt);
            //</snippet10>

            //<snippet11>
            var syllable = "ha";
            var laugh    = "";

            for (var i = 0; i < 10; i++)
            {
                laugh += syllable;
                Console.WriteLine(laugh);
            }
            //</snippet11>

            //<snippet12>
            foreach (char ch in laugh)
            {
                if (ch == 'h')
                {
                    Console.Write("H");
                }
                else
                {
                    Console.Write(ch);
                }
            }
            Console.WriteLine();
            //</snippet12>

            //<snippet13a>
            string[] vowels1 = { "a", "e", "i", "o", "u" };
            //</snippet13a>
            //<snippet13b>
            var vowels2 = new string[] { "a", "e", "i", "o", "u" };
            //</snippet13b>
            //<snippet13c>
            var vowels3 = new string[5];

            vowels3[0] = "a";
            vowels3[1] = "e";
            // And so on.
            //</snippet13c>


            //<snippet15a>
            ActionExample1("string for x");

            ActionExample2("string for x", "string for y");

            Console.WriteLine($"The value is {FuncExample1("1")}");

            Console.WriteLine($"The sum is {FuncExample2(1, 2)}");
            //</snippet15a>
            //<snippet15b>
            Del exampleDel2 = DelMethod;

            exampleDel2("Hey");
            //</snippet15b>
            //<snippet15c>
            Del exampleDel1 = new Del(DelMethod);

            exampleDel1("Hey");
            //</snippet15c>


            // #16 is below Main.
            Console.WriteLine(GetValueFromArray(vowels1, 1));

            // 17 requires System.Drawing
            //<snippet17a>
            Font font1 = new Font("Arial", 10.0f);

            try
            {
                byte charset = font1.GdiCharSet;
            }
            finally
            {
                if (font1 != null)
                {
                    ((IDisposable)font1).Dispose();
                }
            }
            //</snippet17a>
            //<snippet17b>
            using (Font font2 = new Font("Arial", 10.0f))
            {
                byte charset2 = font2.GdiCharSet;
            }
            //</snippet17b>
            //<snippet17c>
            using Font font3 = new Font("Arial", 10.0f);
            byte charset3 = font3.GdiCharSet;

            //</snippet17c>

            //<snippet18>
            Console.Write("Enter a dividend: ");
            int dividend = Convert.ToInt32(Console.ReadLine());

            Console.Write("Enter a divisor: ");
            int divisor = Convert.ToInt32(Console.ReadLine());

            if ((divisor != 0) && (dividend / divisor > 0))
            {
                Console.WriteLine("Quotient: {0}", dividend / divisor);
            }
            else
            {
                Console.WriteLine("Attempted division by 0 ends up here.");
            }
            //</snippet18>


            //<snippet19>
            var instance1 = new ExampleClass();
            //</snippet19>
            // Can't show `ExampleClass instance1 = new()` because this projet targets net48.

            //<snippet20>
            ExampleClass instance2 = new ExampleClass();
            //</snippet20>

            //<snippet21a>
            var instance3 = new ExampleClass {
                Name     = "Desktop", ID = 37414,
                Location = "Redmond", Age = 2.3
            };
            //</snippet21a>
            //<snippet21b>
            var instance4 = new ExampleClass();

            instance4.Name     = "Desktop";
            instance4.ID       = 37414;
            instance4.Location = "Redmond";
            instance4.Age      = 2.3;
            //</snippet21b>

            // #22 and #23 are in Coding_Conventions_WF, below.

            // Save 24 in case we add an example to Static Members.

            ExampleClass.totalInstances = 1;

            var customers = new List <Customer>
            {
                new Customer {
                    Name = "Jones", ID = 432, City = "Redmond"
                }
            };

            // Check shop name to use this.
            var distributors = new List <Distributor>
            {
                new Distributor {
                    Name = "ShopSmart", ID = 11302, City = "Redmond"
                }
            };

            //<snippet25>
            //<snippet28>
            var seattleCustomers = from customer in customers
                                   //</snippet28>
                                   where customer.City == "Seattle"
                                   select customer.Name;
            //</snippet25>

            //<snippet26>
            var localDistributors =
                from customer in customers
                join distributor in distributors on customer.City equals distributor.City
                select new { Customer = customer, Distributor = distributor };
            //</snippet26>

            //<snippet27>
            var localDistributors2 =
                from customer in customers
                join distributor in distributors on customer.City equals distributor.City
                select new { CustomerName = customer.Name, DistributorID = distributor.ID };
            //</snippet27>

            //<snippet29>
            var seattleCustomers2 = from customer in customers
                                    where customer.City == "Seattle"
                                    orderby customer.Name
                                    select customer;
            //</snippet29>

            // #30 is in class CompoundFrom

            var customerDistributorNames =
                from customer in customers
                join distributor in distributors on customer.City equals distributor.City
                select new { CustomerName = customer.Name, DistributorID = distributor.ID };

            var customerDistributorNames2 =
                from customer in customers
                from distributor in distributors
                where customer.City == distributor.City
                select new { CustomerName = customer.Name, DistributorID = distributor.ID };

            foreach (var c in customerDistributorNames)
            {
                Console.WriteLine(c);
            }

            // Could use in Static Members.
            Console.WriteLine(BaseClass.IncrementTotal());
            // Do not do access the static member of the base class through
            // a derived class.
            Console.WriteLine(DerivedClass.IncrementTotal());

            //// Error
            //var instance = new ExampleClass();
            //Console.WriteLine(instance.IncrementTotal());
        }
        public static void CallToSetSealedOnFake(
            DerivedClass fake,
            Exception exception)
        {
            "Given a fake"
                .x(() => fake = A.Fake<DerivedClass>());

            "When I start to configure a sealed property setter on the fake"
                .x(() => exception = Record.Exception(() => A.CallToSet(() => fake.SomeProperty)));

            "Then it throws a fake configuration exception"
               .x(() => exception.Should().BeAnExceptionOfType<FakeConfigurationException>()
                   .And.Message.Should().Contain("Sealed methods can not be intercepted."));
        }
    public static void Main()
    {
        IDerived derived = new DerivedClass();

        derived.ChainableMethod().ChainableMethod();
    }
        public static void CallToSetSealedOnNonFake(
            DerivedClass notAFake,
            Exception exception)
        {
            "Given an object that is not a fake"
                .x(() => notAFake = new DerivedClass());

            "When I start to configure a sealed property setter on the object"
                .x(() => exception = Record.Exception(() => A.CallToSet(() => notAFake.SomeProperty)));

            "Then it throws an argument exception"
               .x(() => exception.Should().BeAnExceptionOfType<ArgumentException>()
                   .And.Message.Should().Contain("The specified object is not recognized as a fake object."));
        }
    public static void Main()
    {
        BaseClass B = new DerivedClass();

        B.Print();
    }
 static void Main()
 {
     DerivedClass md = new DerivedClass();
         DerivedClass md1 = new DerivedClass(1);
 }
 public void Main()
 {
     //here we can call the BaseClass's static method through DerivedClass
     //and it will know what Type calls it
     DerivedClass.Ping();
 }