C#基礎概念二十五問(17-25)[轉貼]

<iframe name="google_ads_frame" marginwidth="0" marginheight="0" src="http://pagead2.googlesyndication.com/pagead/ads?client=ca-pub-1508116105633727&amp;dt=1180749143890&amp;lmt=1180707633&amp;format=728x90_as&amp;output=html&amp;correlator=1180749143880&amp;channel=2744893162&amp;url=http%3A%2F%2Fwww.julysoft.info%2Fself%2F3.htm&amp;ad_type=text_image&amp;flash=9&amp;u_h=768&amp;u_w=1024&amp;u_ah=738&amp;u_aw=1024&amp;u_cd=32&amp;u_tz=480&amp;u_java=true" frameborder="0" width="728" scrolling="no" height="90" allowtransparency="allowtransparency"></iframe>
17.接口的多繼承會帶來哪些問題?

答:

C# 中的接口與類不同,可以使用多繼承,即一個子接口可以有多個父接口。但如果兩個父成員具有同名的成員,就產生了二義性(這也正是 C# 中類取消了多繼承的原因之一),這時在實現時最好使用顯式的聲明

示例:

using System;
using System.Collections.Generic;
using System.Text;
 
namespace Example17
{
    class Program
    {
        //一個完整的接口聲明示例
        interface IExample
        {
            //屬性
            string P
            {
                get;
                set;
            }
            //方法
            string F(int Value);
            //事件
            event EventHandler E;
            //索引指示器
            string this[int Index]
            {
                get;
                set;
            }
        }
        interface IA
        {
            int Count { get; set;}
        }
        interface IB
        {
            int Count();
        }
        //IC接口從IA和IB多重繼承
        interface IC : IA, IB
        {
        }
        class C : IC
        {
            private int count = 100;
            //顯式聲明實現IA接口中的Count屬性
            int IA.Count
            {
                get { return 100; }
                set { count = value; }
            }
            //顯式聲明實現IB接口中的Count方法
            int IB.Count()
            {
                return count * count;
            }
        }
        static void Main(string[] args)
        {
            C tmpObj = new C();
 
            //調用時也要顯式轉換
            Console.WriteLine("Count property: {0}", ((IA)tmpObj).Count);
            Console.WriteLine("Count function: {0}", ((IB)tmpObj).Count());
 
            Console.ReadLine();
        }
    }
}

結果:
Count property: 100
Count function: 10000


18.抽象類和接口的區別?

答:

抽象類(abstract class)可以包含功能定義和實現,接口(interface)只能包含功能定義

抽象類是從一系列相關對象中抽象出來的概念, 因此反映的是事物的內部共性;接口是爲了滿足外部調用而定義的一個功能約定, 因此反映的是事物的外部特性

分析對象,提煉內部共性形成抽象類,用以表示對象本質,即“是什麼”

爲外部提供調用或功能需要擴充時優先使用接口


19.別名指示符是什麼?

答:

通過別名指示符我們可以爲某個類型起一個別名

主要用於解決兩個命名空間內有同名類型的衝突或避免使用冗餘的命名空間

別名指示符只在一個單元文件內起作用

示例:

Class1.cs:

using System;
using System.Collections.Generic;
using System.Text;
 
namespace com.nblogs.reonlyrun.CSharp26QExample.Example19.Lib01
{
    class Class1
    {
        public override string ToString()
        {
            return "com.nblogs.reonlyrun.CSharp26QExample.Example19.Lib01's Class1";
        }
    }
}

Class2.cs

using System;
using System.Collections.Generic;
using System.Text;
 
namespace com.nblogs.reonlyrun.CSharp26QExample.Example19.Lib02
{
    class Class1
    {
        public override string ToString()
        {
            return "com.nblogs.reonlyrun.CSharp26QExample.Example19.Lib02's Class1";
        }
    }
}

主單元(Program.cs):

using System;
using System.Collections.Generic;
using System.Text;
 
//使用別名指示符解決同名類型的衝突
using Lib01Class1 = com.nblogs.reonlyrun.CSharp26QExample.Example19.Lib01.Class1;
using Lib02Class2 = com.nblogs.reonlyrun.CSharp26QExample.Example19.Lib02.Class1;
 
namespace Example19
{
    class Program
    {
        static void Main(string[] args)
        {
            Lib01Class1 tmpObj1 = new Lib01Class1();
            Lib02Class2 tmpObj2 = new Lib02Class2();
 
            Console.WriteLine(tmpObj1);
            Console.WriteLine(tmpObj2);
 
            Console.ReadLine();
        }
    }
}

結果:
com.nblogs.reonlyrun.CSharp26QExample.Example19.Lib01's Class1
com.nblogs.reonlyrun.CSharp26QExample.Example19.Lib02's Class1

 

20.如何釋放非託管資源?

答:

 .NET 平臺在內存管理方面提供了GC(Garbage Collection),負責自動釋放託管資源和內存回收的工作,但它無法對非託管資源進行釋放,這時我們必須自己提供方法來釋放對象內分配的非託管資源,比如你在對象的實現代碼中使用了一個COM對象

最簡單的辦法,可以通過實現protected void Finalize()(析構函數會在編譯時變成這個東東)來釋放非託管資源,因爲GC在釋放對象時會檢查該對象是否實現了 Finalize() 方法,如果是則調用它。但,據說這樣會降低效率。。。

有一種更好的,那就是通過實現一個接口顯式的提供給客戶調用端手工釋放對象的方法,而不是傻傻的等着GC來釋放我們的對象(何況效率又那麼低)

System 命名空間內有一個 IDisposable 接口,拿來做這事非常合適,就省得我們自己再聲明一個接口了

另外補充一句,這種實現並不一定要使用了非託管資源後才用,如果你設計的類會在運行時有大些的實例(象 GIS 中的Geometry),爲了優化程序性能,你也可以通過實現該接口讓客戶調用端在確認不需要這些對象時手工釋放它們

示例:

using System;
using System.Collections.Generic;
using System.Text;
 
namespace Example20
{
    class Program
    {
        class Class1 : IDisposable
        {
            //析構函數,編譯後變成 protected void Finalize(),GC會在回收對象前會調用調用該方法
            ~Class1()
            {
                Dispose(false);
            }
 
            //通過實現該接口,客戶可以顯式地釋放對象,而不需要等待GC來釋放資源,據說那樣會降低效率
            void IDisposable.Dispose()
            {
                Dispose(true);
            }
 
            //將釋放非託管資源設計成一個虛函數,提供在繼承類中釋放基類的資源的能力
            protected virtual void ReleaseUnmanageResources()
            {
                //Do something...
            }
 
            //私有函數用以釋放非託管資源
            private void Dispose(bool disposing)
            {
                ReleaseUnmanageResources();
 
                //爲true時表示是客戶顯式調用了釋放函數,需通知GC不要再調用對象的Finalize方法
                //爲false時肯定是GC調用了對象的Finalize方法,所以沒有必要再告訴GC你不要調用我的Finalize方法啦
                if (disposing)
                {
                    GC.SuppressFinalize(this);
                }
            } 
        }
        static void Main(string[] args)
        {
            //tmpObj1沒有手工釋放資源,就等着GC來慢慢的釋放它吧
            Class1 tmpObj1 = new Class1();
 
            //tmpObj2調用了Dispose方法,傳說比等着GC來釋放它效率要調一些
            //個人認爲是因爲要逐個對象的查看其元數據,以確認是否實現了Dispose方法吧
            //當然最重要的是我們可以自己確定釋放的時間以節省內存,優化程序運行效率
            Class1 tmpObj2 = new Class1();
            ((IDisposable)tmpObj2).Dispose();
        }
    }
}


21.P/Invoke是什麼?

答:

在受控代碼與非受控代碼進行交互時會產生一個事務(transition) ,這通常發生在使用平臺調用服務(Platform Invocation Services),即P/Invoke

如調用系統的 API 或與 COM 對象打交道,通過 System.Runtime.InteropServices 命名空間

雖然使用 Interop 非常方便,但據估計每次調用事務都要執行 10 到 40 條指令,算起來開銷也不少,所以我們要儘量少調用事務

如果非用不可,建議本着一次調用執行多個動作,而不是多次調用每次只執行少量動作的原則

 

22.StringBuilder 和 String 的區別?

答:

String 雖然是一個引用類型,但在賦值操作時會產生一個新的對象,而 StringBuilder 則不會

所以在大量字符串拼接或頻繁對某一字符串進行操作時最好使用 StringBuilder,不要使用 String

示例:

using System;
using System.Collections.Generic;
using System.Text;
 
namespace Example22
{
    class Program
    {
        static void Main(string[] args)
        {
            const int cycle = 100000;
 
            long vTickCount = Environment.TickCount;
            String str = null;
            for (int i = 0; i < cycle; i++)
                str += i.ToString();
            Console.WriteLine("String: {0} MSEL", Environment.TickCount - vTickCount);
 
            vTickCount = Environment.TickCount;
            //看到這個變量名我就生氣,奇怪爲什麼大家都使它呢? :)
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < cycle; i++)
                sb.Append(i);
            Console.WriteLine("StringBuilder: {0} MSEL", Environment.TickCount - vTickCount);
 
            Console.ReadLine();
        }
    }
}

結果:
String: 102047 MSEL
StringBuilder: 46 MSEL

23.explicit 和 implicit 的含義?

答:

explicit 和 implicit 屬於轉換運算符,如用這兩者可以讓我們自定義的類型支持相互交換

explicti 表示顯式轉換,如從 A -> B 必須進行強制類型轉換(B = (B)A)

implicit 表示隱式轉換,如從 B -> A 只需直接賦值(A = B)

隱式轉換可以讓我們的代碼看上去更漂亮、更簡潔易懂,所以最好多使用 implicit 運算符。不過!如果對象本身在轉換時會損失一些信息(如精度),那麼我們只能使用 explicit 運算符,以便在編譯期就能警告客戶調用端

示例: 

using System;
using System.Collections.Generic;
using System.Text;
 
namespace Example23
{
    class Program
    {
        //本例靈感來源於大話西遊經典臺詞“神仙?妖怪?”--主要是我實在想不出什麼好例子了
        class Immortal
        {
            public string name;
            public Immortal(string Name)
            {
                name = Name;
            }
            public static implicit operator Monster(Immortal value)
            {
                return new Monster(value.name + ":神仙變妖怪?偷偷下凡即可。。。");
            }
        }
        class Monster
        {
            public string name;
            public Monster(string Name)
            {
                name = Name;
            }
            public static explicit operator Immortal(Monster value)
            {
                return new Immortal(value.name + ":妖怪想當神仙?再去修煉五百年!");
            }
        }
        static void Main(string[] args)
        {
            Immortal tmpImmortal = new Immortal("紫霞仙子");
            //隱式轉換
            Monster tmpObj1 = tmpImmortal;
            Console.WriteLine(tmpObj1.name);
 
            Monster tmpMonster = new Monster("孫悟空");
            //顯式轉換
            Immortal tmpObj2 = (Immortal)tmpMonster;
            Console.WriteLine(tmpObj2.name);
 
            Console.ReadLine();
        }
    }
}

結果:
紫霞仙子:神仙變妖怪?偷偷下凡即可。。。
孫悟空:妖怪想當神仙?再去修煉五百年!


24.params 有什麼用?

答:

params 關鍵字在方法成員的參數列表中使用,爲該方法提供了參數個數可變的能力

它在只能出現一次並且不能在其後再有參數定義,之前可以

示例:

using System;
using System.Collections.Generic;
using System.Text;
 
namespace ConsoleApplication1
{
    class App
    {
        //第一個參數必須是整型,但後面的參數個數是可變的。
        //而且由於定的是object數組,所有的數據類型都可以做爲參數傳入
        public static void UseParams(int id, params object[] list)
        {
            Console.WriteLine(id);
            for (int i = 0; i < list.Length; i++)
            {
                Console.WriteLine(list[i]);
            }
        }
 
        static void Main()
        {
            //可變參數部分傳入了三個參數,都是字符串類型
            UseParams(1, "a", "b", "c");
            //可變參數部分傳入了四個參數,分別爲字符串、整數、浮點數和雙精度浮點數數組
            UseParams(2, "d", 100, 33.33, new double[] { 1.1, 2.2 });
 
            Console.ReadLine();
        }
    }
}

結果:
1
a
b
c
2
d
100
33.33
System.Double[]


25.什麼是反射?

答:

反射,Reflection,通過它我們可以在運行時獲得各種信息,如程序集、模塊、類型、字段、屬性、方法和事件

通過對類型動態實例化後,還可以對其執行操作

一般用於插件式框架程序和設計模式的實現,當然反射是一種手段可以充分發揮其能量來完成你想做的任何事情(前面好象見過一位高人用反射調用一個官方類庫中未說明的函數。。。)

示例:

using System;
using System.Collections.Generic;
using System.Text;
 
namespace Example25Lib
{
    public class Class1
    {
        private string name;
        private int age;
 
        //如果顯式的聲明瞭無參數構造函數,客戶端只需要用程序集的CreateInstance即可實例化該類
        //在此特意不實現,以便在客戶調用端體現構造函數的反射實現
        //public Class1()
        //{
        //}
        public Class1(string Name, int Age)
        {
            name = Name;
            age = Age;
        }
        public void ChangeName(string NewName)
        {
            name = NewName;
        }
        public void ChangeAge(int NewAge)
        {
            age = NewAge;
        }
        public override string ToString()
        {
            return string.Format("Name: {0}, Age: {1}", name, age);
        }
    }
}

反射實例化對象並調用其方法,屬性和事件的反射調用略去

using System;
using System.Collections.Generic;
using System.Text;
 
//注意添加該反射的命名空間
using System.Reflection;
 
namespace Example25
{
    class Program
    {
        static void Main(string[] args)
        {
            //加載程序集
            Assembly tmpAss = Assembly.LoadFile(AppDomain.CurrentDomain.BaseDirectory + "Example25Lib.dll");
 
            //遍歷程序集內所有的類型,並實例化
            Type[] tmpTypes = tmpAss.GetTypes();
            foreach (Type tmpType in tmpTypes)
            {
                //獲取第一個類型的構造函數信息
                ConstructorInfo[] tmpConsInfos = tmpType.GetConstructors();
                foreach (ConstructorInfo tmpConsInfo in tmpConsInfos)
                {
                    //爲構造函數生成調用的參數集合
                    ParameterInfo[] tmpParamInfos = tmpConsInfo.GetParameters(); 
                    object[] tmpParams = new object[tmpParamInfos.Length];
                    for (int i = 0; i < tmpParamInfos.Length; i++)
                    {
                        tmpParams[i] = tmpAss.CreateInstance(tmpParamInfos[i].ParameterType.FullName);
                        if (tmpParamInfos[i].ParameterType.FullName == "System.String")
                        {
                            tmpParams[i] = "Clark";
                        }
                    }
 
                    //實例化對象
                    object tmpObj = tmpConsInfo.Invoke(tmpParams);
                    Console.WriteLine(tmpObj);
 
                    //獲取所有方法並執行
                    foreach (MethodInfo tmpMethod in tmpType.GetMethods())
                    {
                        //爲方法的調用創建參數集合
                        tmpParamInfos = tmpMethod.GetParameters();
                        tmpParams = new object[tmpParamInfos.Length];
                        for (int i = 0; i < tmpParamInfos.Length; i++)
                        {
                            tmpParams[i] = tmpAss.CreateInstance(tmpParamInfos[i].ParameterType.FullName);
                            if (tmpParamInfos[i].ParameterType.FullName == "System.String")
                            {
                                tmpParams[i] = "Clark Zheng";
                            }
                            if (tmpParamInfos[i].ParameterType.FullName == "System.Int32")
                            {
                                tmpParams[i] = 27;
                            }
                        }
                        tmpMethod.Invoke(tmpObj, tmpParams);
                    }
 
                    //調用完方法後再次打印對象,比較結果
                    Console.WriteLine(tmpObj);
                }
            }
 
            Console.ReadLine();
        }
    }
}

結果:
Name: Clark, Age: 0
Name: Clark Zheng, Age: 27

 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章