2014-11-25 70 views
0

這是一個由例子,所以不要對我嚷嚷,這是一個不好的設計:)如何在屬性中提供對成員字段的引用?

假設我有:

class UserInfo 
{ 
    SomeType1 member1; 

    SomeType2 member2; 

    SomeType3 member3; 


    Guid idInDB1; 

    Guid idInDB2; 
} 

每個成員無論是在DB1或DB2保存(不兩者),並且對於每個成員,我想提供一個指向包含數據庫標識的變量的屬性。例如:

[DBReference(idInDB1)] 

這可能嗎?

+1

屬性是元數據,他們居住的類型或成員,它沒有任何內容的定義。根據定義,您必須能夠通過知道其使用的成員的類型而不是實際的實例來獲取屬性中的值。既然如此,你就沒有辦法將這個屬性鏈接到實際數據。你可以做的是將數據庫名稱指定爲字符串或使用枚舉。 – 2014-11-25 08:40:57

+0

屬性值必須是編譯時間常量,這意味着它們在編譯時最爲人知,因爲它們被視爲元數據。你可以看看[這](http://stackoverflow.com/questions/14230414/c-workaround-for-setting-non-constant-value-to-an-attribute)一些hacky變通辦法,我不會推薦。 – 2014-11-25 08:41:04

+0

@YuvalItzchakov我想提供一個變量的參考,而不是它的值 – Shmoopy 2014-11-25 08:42:04

回答

0

由於Guid s不能編譯時間常量,因此使用string更容易,並將其轉換爲屬性中的Guid

考慮這樣的事情:

public class DBReferenceAttribute : Attribute 
{ 
    public DBReferenceAttribute(string guid) 
    { 
     this.Guid = new Guid(guid); 
    } 

    public Guid Guid { get; set; } 
} 

class UserInfo 
{ 
    [DBReference(idInDB1)] 
    string member1; 

    string member2; 

    string member3; 


    const string idInDB1 = "000"; 
} 
+0

我應該如何定義DBReference構造函數? – Shmoopy 2014-11-25 08:57:18

+0

請注意,idInDB1不是一個常量,我只知道它在運行時 – Shmoopy 2014-11-25 09:01:04

+0

@Shmoopy:請參閱代碼中的構造函數。 – 2014-11-25 09:02:24

相關問題