csharp: Use of Is and As operators in csharp

       /// <summary>
        /// Geovin Du 20170622
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            Object o = new Object();
            System.Boolean b1 = (o is System.Object);//b1 为true
            System.Boolean b2 = (o is Employee);//b2为false

            if (o is Employee)
            {
                Employee em = (Employee)o;
                em.RealName = "geovindu";
                MessageBox.Show(em.RealName);
            }
            else
            {
                MessageBox.Show("no"); //结果为显示NO
            }
            Object obj;
            Employee employee = new Employee();
            employee.RealName = "du";
            employee.Birthday = DateTime.Now;
            employee = o as Employee;
            obj = o as Employee;
           
            if (employee != null)
            {
                //在if语句中使用e
                MessageBox.Show(employee.RealName);
            }
            else
            {
                MessageBox.Show("no2");  //结果为显示NO2
            }

        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {
            var c1 = "";
            var c2 = typeof(string);
            object oc1 = c1;
            object oc2 = c2;

            var s1 = 0;
            var s2 = '.';
            object os1 = s1;
            object os2 = s2;

            bool b = false;

            Stopwatch sw = Stopwatch.StartNew();
            for (int i = 0; i < 10000000; i++)
            {
                b = c1.GetType() == typeof(string); // ~60ms
                b = c1 is string; // ~60ms

                b = c2.GetType() == typeof(string); // ~60ms
                b = c2 is string; // ~50ms

                b = oc1.GetType() == typeof(string); // ~60ms
                b = oc1 is string; // ~68ms

                b = oc2.GetType() == typeof(string); // ~60ms
                b = oc2 is string; // ~64ms


                b = s1.GetType() == typeof(int); // ~130ms
                b = s1 is int; // ~50ms

                b = s2.GetType() == typeof(int); // ~140ms
                b = s2 is int; // ~50ms

                b = os1.GetType() == typeof(int); // ~60ms
                b = os1 is int; // ~74ms

                b = os2.GetType() == typeof(int); // ~60ms
                b = os2 is int; // ~68ms


                b = GetType1<string, string>(c1); // ~178ms
                b = GetType2<string, string>(c1); // ~94ms
                b = Is<string, string>(c1); // ~70ms

                b = GetType1<string, Type>(c2); // ~178ms
                b = GetType2<string, Type>(c2); // ~96ms
                b = Is<string, Type>(c2); // ~65ms

                b = GetType1<string, object>(oc1); // ~190ms
                b = Is<string, object>(oc1); // ~69ms

                b = GetType1<string, object>(oc2); // ~180ms
                b = Is<string, object>(oc2); // ~64ms


                b = GetType1<int, int>(s1); // ~230ms
                b = GetType2<int, int>(s1); // ~75ms
                b = Is<int, int>(s1); // ~136ms

                b = GetType1<int, char>(s2); // ~238ms
                b = GetType2<int, char>(s2); // ~69ms
                b = Is<int, char>(s2); // ~142ms

                b = GetType1<int, object>(os1); // ~178ms
                b = Is<int, object>(os1); // ~69ms

                b = GetType1<int, object>(os2); // ~178ms
                b = Is<int, object>(os2); // ~69ms
            }

            sw.Stop();
            MessageBox.Show(sw.Elapsed.TotalMilliseconds.ToString());
        }
        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="S"></typeparam>
        /// <typeparam name="T"></typeparam>
        /// <param name="t"></param>
        /// <returns></returns>
        static bool GetType1<S, T>(T t)
        {
            return t.GetType() == typeof(S);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="S"></typeparam>
        /// <typeparam name="T"></typeparam>
        /// <param name="t"></param>
        /// <returns></returns>
        static bool GetType2<S, T>(T t)
        {
            return typeof(T) == typeof(S);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="S"></typeparam>
        /// <typeparam name="T"></typeparam>
        /// <param name="t"></param>
        /// <returns></returns>
        static bool Is<S, T>(T t)
        {
            return t is S;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button3_Click(object sender, EventArgs e)
        {
            var cl1 = new Class1();
            if (cl1 is IFormatProvider)
            {
                MessageBox.Show("cl1 is IFormatProvider ok");
            }
            else
            {
                MessageBox.Show("cl1 is IFormatProvider no");
            }
            if (cl1 is Object)
            {
                MessageBox.Show("cl1 is Object ok");
            }
            else
            {
                MessageBox.Show("cl1 is Object no");
            }
            if (cl1 is Class1)
            {
                MessageBox.Show("cl1 is Class1 ok");
            }
            else
            {
                MessageBox.Show("cl1 is Class1 no");
            }
            if (cl1 is Class2)
            {
                MessageBox.Show("cl1 is Class2 ok");
            }
            else
            {
                MessageBox.Show("cl1 is Class2 no");
            }


            var cl2 = new Class2();
            if (cl2 is IFormatProvider)
            {
                MessageBox.Show("cl2 is IFormatProvider ok");
            }
            else
            {
                MessageBox.Show("cl2 is IFormatProvider no");
            }
            if (cl2 is Class2)
            {
                MessageBox.Show("cl2 is Class2 ok"); 
            }
            else
            {
                MessageBox.Show("cl2 is Class2 no");
            }
            if (cl2 is Class1)
            {
                MessageBox.Show("cl2 is Class1 ok");
            }
            else
            {
                MessageBox.Show("cl2 is Class1 no");
            }
     

            Class1 cl = cl2;
            if (cl is Class1) 
            {
                MessageBox.Show("cl is Class1 ok"); 
            }
            else
            {
                MessageBox.Show("cl is Class1 no");
            };
            if(cl is Class2)
            {
                MessageBox.Show("cl is Class2 ok"); 
            }
            else
            {
                MessageBox.Show("cl is Class2 no");
            };

            bool isc1 = (cl is Class1);
            if (isc1)
            {
                MessageBox.Show("true");
            }

        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button4_Click(object sender, EventArgs e)
        {
            Object o = new Person("Jane");
            ShowValue(o);

            o = new Dog("Alaskan Malamute");
            ShowValue(o);

            Employee em = new Employee();
            em.RealName = "geovindu";
            em.Birthday = DateTime.Now;
            o =em;
            ShowValue(o);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="o"></param>
        public static void ShowValue(object o)
        {
            if (o is Person)
            {
                Person p = (Person)o;
                MessageBox.Show(p.Name);
            }
            else if (o is Dog)
            {
                Dog d = (Dog)o;
                MessageBox.Show(d.Breed);
            }
            else
            {
                MessageBox.Show("啥也不是");
            }
        }

    }
    /// <summary>
    /// 
    /// </summary>
    public class Class1 : IFormatProvider
    {
        public object GetFormat(Type t)
        {
            if (t.Equals(this.GetType()))
                return this;
            return null;
        }
    }
    /// <summary>
    /// 
    /// </summary>
    public class Class2 : Class1
    {
        public int Value { get; set; }
    }
    /// <summary>
    /// 员工
    /// </summary>
    public class Employee
    {     
        /// <summary>
        /// 真名
        /// </summary>
        public string RealName { set; get; }       
        /// <summary>
        /// 出生日期
        /// </summary>
        public DateTime Birthday { set; get; }
    }
    /// <summary>
    /// 
    /// </summary>
    public struct Person
    {
        public string Name { get; set; }

        public Person(string name)
            : this()
        {
            Name = name;
        }
    }
    /// <summary>
    /// 
    /// </summary>
    public struct Dog
    {
        public string Breed { get; set; }

        public Dog(string breedName)
            : this()
        {
            Breed = breedName;
        }
    }

  

TypeInfo,PropertyInfo,MethodInfo,FieldInfo

        /// <summary>
        /// Geovin Du 涂聚文
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button5_Click(object sender, EventArgs e)
        {
            Int32 indent = 0;
            // Display information about each assembly loading into this AppDomain.
            foreach (Assembly b in AppDomain.CurrentDomain.GetAssemblies())
            {
                Display(indent, "Assembly: {0}", b);

                // Display information about each module of this assembly.
                foreach (Module m in b.GetModules(true))
                {
                    Display(indent + 1, "Module: {0}", m.Name);
                }

                // Display information about each type exported from this assembly.

                indent += 1;
                foreach (Type t in b.GetExportedTypes())
                {
                    Display(0, "");
                    Display(indent, "Type: {0}", t);

                    // For each type, show its members & their custom attributes.

                    indent += 1;
                    foreach (MemberInfo mi in t.GetMembers())
                    {
                        Display(indent, "Member: {0}", mi.Name);
                        DisplayAttributes(indent, mi);

                        // If the member is a method, display information about its parameters.

                        if (mi.MemberType == MemberTypes.Method)
                        {
                            foreach (ParameterInfo pi in ((MethodInfo)mi).GetParameters())
                            {
                                Display(indent + 1, "Parameter: Type={0}, Name={1}", pi.ParameterType, pi.Name);
                            }
                        }

                        // If the member is a property, display information about the property's accessor methods.
                        if (mi.MemberType == MemberTypes.Property)
                        {
                            foreach (MethodInfo am in ((PropertyInfo)mi).GetAccessors())
                            {
                                Display(indent + 1, "Accessor method: {0}", am);
                            }
                        }
                    }
                    indent -= 1;
                }
                indent -= 1;
            }
        }


        /// <summary>
        /// Displays the custom attributes applied to the specified member.
        /// </summary>
        /// <param name="indent"></param>
        /// <param name="mi"></param> 
        public static void DisplayAttributes(Int32 indent, MemberInfo mi)
        {
            // Get the set of custom attributes; if none exist, just return.
            object[] attrs = mi.GetCustomAttributes(false);
            if (attrs.Length == 0) { return; }

            // Display the custom attributes applied to this member.
            Display(indent + 1, "Attributes:");
            foreach (object o in attrs)
            {
                Display(indent + 2, "{0}", o.ToString());
            }
        }
        /// <summary>
        /// Display a formatted string indented by the specified amount.
        /// </summary>
        /// <param name="indent"></param>
        /// <param name="format"></param>
        /// <param name="param"></param> 
        public static void Display(Int32 indent, string format, params object[] param)
        {
            string st = new string(' ', indent * 2);
            MessageBox.Show(st);
            string s=string.Format("format:{0},param:{1}.",format, param);
            MessageBox.Show(s);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button6_Click(object sender, EventArgs e)
        {
          // System.Reflection.MemberTypes
            //4.6,4.5 .net
            //TypeInfo t = typeof(Calendar).GetTypeInfo();
            //4.6,4.5
            // IEnumerable<PropertyInfo> pList = t.DeclaredProperties;
            //4.5,4.6
            //IEnumerable<MethodInfo> mList = t.DeclaredMethods;         

            //4.0
            IEnumerable<PropertyInfo> pList = typeof(Calendar).GetProperties();
            IEnumerable<MethodInfo> mList = typeof(Calendar).GetMethods();
            IEnumerable<FieldInfo> fList = typeof(Calendar).GetFields();

            StringBuilder sb = new StringBuilder();
            sb.Append("Properties:");
            foreach (PropertyInfo p in pList)
            {

                sb.Append("\n" + p.DeclaringType.Name + ": " + p.Name);
            }
            sb.Append("\nMethods:");
            foreach (MethodInfo m in mList)
            {
                sb.Append("\n" + m.DeclaringType.Name + ": " + m.Name);
            }
            MessageBox.Show(sb.ToString());
        }

  

posted @ 2017-06-22 10:24  ®Geovin Du Dream Park™  阅读(450)  评论(0编辑  收藏  举报