2017-02-09 90 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

相关问题