2012-04-26 67 views
1

我想提取屬性。屬性是自定義屬性。 enter image description here 但一些我怎麼不能使用object.id的事情。
例如,我的評論代碼adpter.id無效,即使您看到我已將該對象轉換爲其類型。無法提取屬性數據

下面是屬性代碼:

[AttributeUsage(AttributeTargets.All, AllowMultiple = true, Inherited = true)] 
public class Adapter : Attribute 
{ 
    // This class implements the Adapter Attribite 
    readonly int id; 
    readonly string Title; 
    public string Comment { get; set; } 

    private string[] Relation; 

    public Adapter(int id, string Title,string []relations) 
    { 
     this.id = id; 
     this.Title = Title; 
     this.Relation = relations; 
    } 


} 
+1

除了下面的答案,您應該爲您的類型使用「-Attribute」後綴,派生自System.Attribute。例如。 「AdapterAttribute」。 – Dennis 2012-04-26 08:45:35

回答

4

的字段的默認能見度是私有的,儘量讓idTitle公衆。
你也可以改變字段屬性,像這樣的私人二傳手:

public Id { get; private set; } 
public Title { get; private set; } 

或者以只讀屬性:

public Id { get { return id; } } 
public Title { get { return title; } } 

因爲它被認爲是不好的設計創造公共領域。

+1

這不是隻讀屬性。這是私人二傳手的財產。他們之間有區別。 – Dennis 2012-04-26 08:43:43

+0

這是正確的,我的不好。只讀屬性沒有setter。更新的答案反映了這一點。 – Xharze 2012-04-26 08:46:35

+0

那麼'public readonly Id'和'public Id'有什麼區別? – Cancer 2012-04-26 08:47:27

1

你想從另一個類讀取ID? 您缺少公共修飾符。

public readonly int id; 

缺失修飾符的變量,屬性和方法將自動變爲隱私。

希望這會有所幫助!

1

我猜給出一個類的默認行爲,如私有成員,你可以嘗試將其更改爲public