2017-02-09 135 views
0

我可能錯誤地問了這個問題,但請堅持在這裏。如何在繼承類中設置同名但不同類型的屬性

我想提出的是有幾個規則配置管理器..所有Keys是字符串,但Value可以是stringintdoublebool(但顯示爲0.1整數)

我已經寫了一個類和一些通用的東西,也覆蓋ToString();方法來獲得一個很好的印刷模式和包裝類我創建了一個運算符覆蓋獲取對象。現在,我想創建一個setter爲對象,但我有,因爲值不匹配的類型,一些嚴重的麻煩..

public class Config() 
{ 
    public List<ConfigEntry> ConfigLines {get;set;} 

    public ConfigEntry this[string key] 
    { 
     get 
     { 
      if(CfgConfig.Any(x => x.GetKey(true) == key)) 
      { 
       return CfgConfig.Where(x => x.GetKey(true) == key).Single(); 
      } 
      if (ProfileConfig.Any(x => x.GetKey(true) == key)) 
      { 
       return ProfileConfig.Where(x => x.GetKey(true) == key).Single(); 
      } 

      return null; 
     } 
     set 
     { 
      //?????????????? 
     } 
    } 

    public class ConfigEntry() 
    { 
     public string CommonStuff {get;set); 

     public virtual string GetKey(bool tolower = false) 
     { 
      return null; 
     } 

     public override string ToString() 
     { 
      return CommonStuff; 
     } 

     public class TextValue : ConfigEntry 
     { 
      public string Key {get;set;} 
      public string Value {get;set;} 

      public override string ToString() 
      { 
      return [email protected]"{Key}={Value};"; 
      } 

      public virtual string GetKey(bool tolower = false) 
      { 
       if (tolower) 
        return Key.ToLower(); 
       else 
        return Key; 
      } 
     } 

     public class IntValue : ConfigEntry 
     { 
      public string Key {get;set;} 
      public int Value {get;set;} 

      public override string ToString() 
      { 
       return [email protected]"{Key}={Value};"; 
      } 

      public virtual string GetKey(bool tolower = false) 
      { 
       if (tolower) 
        return Key.ToLower(); 
       else 
        return Key; 
      } 
     } 
    } 
} 

現在我怎麼能配置運營商[那二傳手]這實際上正常工作,如果我輸入,讓說ConfigLines["anintkey"] = 5;ConfigLines["astringkey"] = "Hello";,這兩件事情工作..我想,我確實需要在這裏使用<T> class某處,但我沒有使用模板很多,我可以我想不出一種方法來解決這個問題。 我確實希望將原始列表保留爲基類,然後從中繼續工作,但我不知道如何解決這個問題。

謝謝大家的幫助!

回答

1

您可以製作ConfigEntry<T>,但您將被迫製作Config<T>其中包含List<ConfigEntry<T>>。所以這不是解決方案。

所有你需要的僅僅是dynamic

var conf = new Dictionary<string, dynamic>(); 
conf["url"] = "http://example.com"; 
conf["timeout"] = 30; 
// in some other place 
string url = conf["url"]; 
int timeout = conf["timeout"]; 
+0

我使用的字典在我的舊版本的應用程序,但我要爲一個更強大的解決方案現在..使動態值實際上固定的問題,我只需要檢查是否可以像這樣工作 – DethoRhyne

+0

最健壯的解決方案是創建您需要的所有選項的Config類。如果你不想使用動態,你不會實現這樣的行爲'conf [「url」] =「http://example.com」; conf [「timeout」] = 30;' – Anton

+0

這和你一樣工作說它會的,這對我的情況來說是完美的。謝謝! :)除了我沒有製作字典,我把它留作多個繼承類的對象,並簡單地將Value屬性變爲動態類型 – DethoRhyne

相關問題