C#基礎(chǔ)概念總結(jié)
C#基礎(chǔ)概念之接口的多繼承會(huì)帶來(lái)哪些問(wèn)題?
C# 中的接口與類(lèi)不同,可以使用多繼承,即一個(gè)子接口可以有多個(gè)父接口。但如果兩個(gè)父成員具有同名的成員,就產(chǎn)生了二義性(這也正是 C# 中類(lèi)取消了多繼承的原因之一),這時(shí)在實(shí)現(xiàn)時(shí)最好使用顯式的聲明
示例:
- using System;
- using System.Collections.Generic;
- using System.Text;
- namespace Example17 {
- class Program {
- //一個(gè)完整的接口聲明示例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;
- //顯式聲明實(shí)現(xiàn)IA接口中的Count屬性int IA.Count {
- get {
- return 100;
- }
- set { count = value; }
- }
- //顯式聲明實(shí)現(xiàn)IB接口中的Count方法int IB.Count(){
- return count * count;} static void Main(string[] args){
- C tmpObj = new C();
- //調(diào)用時(shí)也要顯式轉(zhuǎn)換Console.WriteLine("Count property: {0}",((IA)tmpObj)。Count);
- Console.WriteLine("Count function: {0}",((IB)tmpObj)。Count());
- Console.ReadLine();
- }
C#基礎(chǔ)概念之抽象類(lèi)和接口的區(qū)別?
抽象類(lèi)(abstract class)可以包含功能定義和實(shí)現(xiàn),接口(interface)只能包含功能定義,抽象類(lèi)是從一系列相關(guān)對(duì)象中抽象出來(lái)的概念, 因此反映的是事物的內(nèi)部共性;接口是為了滿(mǎn)足外部調(diào)用而定義的一個(gè)功能約定, 因此反映的是事物的外部特性,分析對(duì)象,提煉內(nèi)部共性形成抽象類(lèi),用以表示對(duì)象本質(zhì),即“是什么”,為外部提供調(diào)用或功能需要擴(kuò)充時(shí)優(yōu)先使用接口
C#基礎(chǔ)概念之別名指示符是什么?
通過(guò)別名指示符我們可以為某個(gè)類(lèi)型起一個(gè)別名,主要用于解決兩個(gè)命名空間內(nèi)有同名類(lèi)型的沖突或避免使用冗余的命名空間,別名指示符只在一個(gè)單元文件內(nèi)起作用
示例:
- 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;
- //使用別名指示符解決同名類(lèi)型的沖突
- 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();
- }
【編輯推薦】