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