2016-02-23 48 views
-1
[ConfigurationProperty("Name", DefaultValue = "test")] 
public string Name 
{ 
    get { return (string)this["Name"]; } 
    set { this["Name"] = "Ram"; } 
} 

CorticonConfig config = new CorticonConfig(); 
string test = config.Name; 

我有一個屬性與「名稱」,我也設置值name.While我嘗試獲取值,我得到默認值。配置DefaultValue行爲

我的問題是:我們可以如上設置屬性值嗎?

Default值屬性的行爲是什麼?

+0

的http://stackoverflow.com/questions/10506323/canonical-example-of-configurationproperty –

+0

類配置 { \t [的ConfigurationProperty( 「姓名」,默認值= 「測試」)] \t公共字符串可能的複製名稱 \t { get {return(string)this [「Name」]; } set {this [「Name」] =「Ram」; } \t} } 類的setValue { \t公共無效的setValue() \t { \t CorticonConfig配置=新CorticonConfig(); \t config.Name =「test」; \t} } 類當前 { \t公共無效的GetValue() \t { \t \t CorticonConfig配置=新CorticonConfig(); \t \t string test = config.Name; \t} } –

+0

這裏我得到了默認值。 –

回答

0

你的財產二傳手不工作,就像你認爲它的工作。

當您設置屬性(你讓property = something),並且在這種情況下,你的something將是對value關鍵字時,執行set部分。

所以你的情況,如果你這樣做:

CorticonConfig config = new CorticonConfig(); 
config.Name = "whatever"; 
string test = config.Name;  

test將有"Ram",因爲你總是asigning該值存在,但除非你做config.Name = <something>也不會執行該代碼。

的正確方法有一個這樣的setter方法是:

set 
    { 
    this["Name"] = value; 
    } 

如果你需要比你在你的屬性設置一個其他的默認值,構造對象之後,應用它:

CorticonConfig config = new CorticonConfig(); 
config.Name = "Ram"; 

如果你沒有保存設置,那麼你傳給該屬性的DefaultValue會給它一個默認值,所以當你閱讀它時,它會返回它。

+0

感謝您的快速回復。但是,爲什麼我獲得默認值? –

+0

我編輯了我的答案,因爲我誤解了你最初的問題 – Jcl

+0

嗨,我已經在其他cs(SetValue)中設置Name屬性(Config.cs)的值。CS)文件,然後在present.cs中重試,但我得到的默認值。 –