csharp: Use of Is and As operators in csharp

来源:http://www.cnblogs.com/geovindu/archive/2017/06/22/7063553.html
-Advertisement-
Play Games

TypeInfo,PropertyInfo,MethodInfo,FieldInfo ...


       /// <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());
        }

  


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 理解資料庫中的事務及其併發過程中的各種限制對於合理的解決數據問題據有著重要意義,否則極有可能出現非常難以排查的由數據導致的程式bug。 ...
  • 6月1日,《中華人民共和國網路安全法》(簡稱《網路安全法》)開始正式實施,這是我國第一部全面規範網路空間安全管理方面問題的基礎性法律。它的頒佈,讓許多互聯網企業以及廣大民眾倍感欣喜。 進入網路時代後,互聯網應用行業發展迅猛,成為推動經濟發展和社會進步的重要力量。然而,發展的同時也帶來了許多新的問題和 ...
  • 一些介紹 CodeFirst是EntityFrameworks的一種開發模式,即代碼優先,它以業務代碼為主,通過代碼來生成資料庫,並且加上migration的強大數據表比對功能來生成資料庫版本,讓程式開發人員不用維護資料庫的變更,而直接維護migration即可,在它裡面有你當前版本和過去歷史版本的 ...
  • // 1. asp頁面使用EasyUI框架需要的Css樣式和JS <script src="../script/jquery-easyui-1.4.5/jquery.min.js" type="text/javascript" charset = "utf-8"></script> <script ...
  • 把一個 dic綁定到了listview上,有時候下拉列表會報這個異常。因為直接使用了itemssource = dic,而dic在另一個線程上不定期更新,這樣如果直接綁定的話就會報這個錯誤,原因是直接綁定的話會把itemssource的記憶體地址直接指向dic的記憶體地址,當dic更新後,會導致記憶體地址 ...
  • 訂單系統設計 總體設計 1.每次下單時間少於3秒 2.庫存驗證不存在多買的情況 3.訂單能夠按照不同供應商進程拆分 4. 物流信息能夠回傳 訂單狀態機設計 1.待系統審核 2.待支付 3.待發貨 4.待簽收 5.已完成 6.訂單關閉 訂單狀態流轉如下圖示: 1)審核失敗 2)未支付(待支付24小時) ...
  • 1.根據單個分隔字元用split截取 例如 即可得到sArray[0]="GT123",sArray[1]="1"; 2.利用多個字元來分隔字元串 例如 得到sArray[0]="GTAZB",sArray[1]="Jiang",sArray[2]="Ben",sArray[3]="123"; 3根 ...
  • 在前端 UI 開發中,有時,我們會遇到這樣的需求:在一個 ScrollViewer 中有很多內容,而我們需要實現在執行某個操作後能夠定位到其中指定的控制項處;這很像在 HTML 頁面中點擊一個鏈接後定位到當前網頁上的某個 anchor。 要實現它,首先我們需要看 ScrollViewer 為我們提供的 ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...