Property和Attribute的區別

Property屬於面向對象理論範疇。在使用面向對象思想編程的時候常常需要對客觀事物進行抽象,再把抽象出來的結果封裝成類,類中用來表示對象狀態的成員就是property

Attribute則是編程語言文法層面的東西,比如有兩個同類的語法元素A和B,爲了區分A和B,就需要加一些Attribute,attribute可以翻譯爲特徵。

在標籤語言中進行面向對象編程時,property也被包裝成爲attribute,但並不意味着所有attribute都是property。

To summarize, attributes support tools that operate on your code, but properties define the state of an object and there is no logical comparison between the two.
總的來說,attribute支撐了你程序中的的各個部分運行,而Properties定義了你的對象的狀態,兩者之間沒有邏輯關係
原文

據博主理解:例如在一個Windows程序中有一個一個CheckBox對象,如果將整個程序視爲一個狀態機,那麼顯然CheckBox的IsChecked和IsEnabled屬性能夠影響程序的運行結果,也即是“決定了對象的狀態”,它們是對象的Attribute,而它們的True或False是對象的Property;

相比之下,它的Name顯然就隻影響這個對象在程序中的名字,至於它是叫“Start”也好還是叫“Kill_Everyone”也好,並不影響程序後臺邏輯的執行,它最多出現在元數據表中,不“決定對象的狀態”,因而沒有Property。但它確實支撐了應用程序的運行,所以依然是對象的Attribute。

或者說得不嚴謹但明白一些,Attribute就是起的那些名字,對象名,變量名,只要表徵着什麼,就是Attribute。

補充一下,如下表所示,在不同範疇內同一概念的不同別名

Description OOA/OOD C++ .NET(C#)/Delphi
Feature Attribute Member Variable Field
Operation Method Member Function Method

可見在C#中的Attribute和OOA/OOD中的含義是略有不同的,在C#中,一個對象包含的所有信息都是它的Attribute,而在OOA/OOD中只有成員變量纔是它的Attribute。

我想現在在C#的範疇內,各位對這兩個概念之間的關係已經基本明朗了,我們在來看看在其他範疇內這兩者的區別在何處

In general terms (and in normal English usage) the terms mean the same thing.
In the specific context of HTML / Javascript the terms get confused because the HTML representation of a DOM element has attributes (that being the term used in XML for the key/value pairs contained within a tag) but when represented as a JavaScript object those attributes appear as object properties.
To further confuse things, changes to the properties will typically update the attributes.
For example, changing the element.href property will update the href attribute on the element, and that’ll be reflected in a call to element.getAttribute(‘href’).
However if you subsequently read that property, it will have been normalised to an absolute URL, even though the attribute might be a relative URL!
原文

可見,同C#中一樣,在HTML中,也可以將Attribute看成是對Property的一種包裝,映射。而Property則代表一個對象的內在狀態。

發佈了25 篇原創文章 · 獲贊 25 · 訪問量 7萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章