MEF學習筆記(4) 宣告匯入

2022-03-07 06:09:33 字數 2161 閱讀 1768

組成部件宣告匯入[system.componentmodel.composition.importattribute]特性。跟匯出類似,有幾個不同的方法即是通過字段,屬性和建構函式。

屬性匯入

為了匯入乙個屬性值,用[system.componentmodel.composition.importattribute]宣告屬性。例如下面的**片段匯入乙個imessagesender

class

program

}

構造函式引數

你也可以通過建構函式的引數指定匯入。這意味著不必給每個匯入新增屬性,你只需要為匯入給建構函式新增引數。為了使用這個,按照下面的步驟進行:

新增乙個[system.componentmodel.composition.importingconstructorattribute]特性到要被mef使用的建構函式。

為每個匯入新增引數到建構函式。

例如下面的**在program類的建構函式匯入乙個message sender

class

program

}

引數匯入

有幾個不同的方法在建構函式定義匯入

1、隱式匯入-預設容器會使用引數的型別去識別契約。例如在下面的借**,imessagesender契約會被使用。

class

program

}

2、顯式匯入-如果你想要指定被匯入的契約,新增[system.componentmodel.composition.importattribute]特性到引數。

字段匯入

mef也支援直接匯入字段值。

class

program

注意:注意匯入或匯出私有成員(字段,屬性和方法)當在完全信任狀態下支援,在中間/區域性資訊狀態可能有問題。

可選擇匯入

mef允許你指定乙個匯入是可選的。當你允許這個,如果它是有效的容器會裝備這個匯出,否則它會設定匯入是default(t).為了使乙個匯入可選,在匯入裡設定allowdefault=true,像下面一樣:

[export]

public

class

ordercontroller

}

ordercontroller可選匯入logger。如果logger不存在,它會設定private _logger為defaultlogger 例項,否則它會使用匯入的logger。

匯入集合

除了單獨匯入外,你可以用importmany特性匯入集合。這意味著所有指定契約的例項會從容器中匯入。

mef部件也可以支援重構。這意味著在容器裡新的匯出變得可行,集合在新設定裡被自動更新。例如下面的notifier類匯入乙個imessagesender集合。這意味著如果有3個imessagesender匯出在容器裡有效,在執行期間他們會被存放到senders屬性裡。

public

class

notifier

public

void notify(string

message)

} }

ipartimportssatisfiednotification

在一些情形下當mef為你的類例項完成匯入過程時你的類被通知對你很重要。如果是這樣,專案要實現[system.componentmodel.composition.ipartimportssatisfiednotification]介面。這個介面只有乙個單獨的方法:onimportssatisfied,當所有匯入可以被滿足和已經滿足時,它會被呼叫。

public

class

program : ipartimportssatisfiednotification

public

void

onimportssatisfied()

}

MEF 程式設計指南(四) 宣告匯入

組合部件通過 system.componentmodel.composition.importattribute 特性宣告匯入。類似於匯出,也有幾種不同的方法宣告匯入,即通過 字段 fields 屬性 properties 和構造器引數 constructor parameters 屬性匯入 pro...

html學習筆記(二) 宣告

宣告有助於瀏覽器中正確顯示網頁。網路上有很多不同的檔案,如果能夠正確宣告html的版本,瀏覽器就能正確顯示網頁內容。所有主流瀏覽器都支援 宣告。宣告位於文件中的最前面的位置,處於 標籤之前。宣告不是乙個 html 標籤 它是用來告知 web 瀏覽器頁面使用了哪種 html 版本。在 html 4.0...

學習筆記 04 宣告和類

宣告 c 的大多數宣告都是從c和c 繼承的。下面的表列出了可用的宣告的型別 宣告 例子 宣告列表和塊宣告 static void main 標號宣告和goto宣告 static void main string args 區域性常量宣告 static void main 區域性變數宣告 static...