我可能错误地问了这个问题,但请坚持在这里。如何在继承类中设置同名但不同类型的属性
我想提出的是有几个规则配置管理器..所有Keys
是字符串,但Value
可以是string
,int
,double
或bool
(但显示为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
某处,但我没有使用模板很多,我可以我想不出一种方法来解决这个问题。 我确实希望将原始列表保留为基类,然后从中继续工作,但我不知道如何解决这个问题。
谢谢大家的帮助!
我使用的字典在我的旧版本的应用程序,但我要为一个更强大的解决方案现在..使动态值实际上固定的问题,我只需要检查是否可以像这样工作 – DethoRhyne
最健壮的解决方案是创建您需要的所有选项的Config类。如果你不想使用动态,你不会实现这样的行为'conf [“url”] =“http://example.com”; conf [“timeout”] = 30;' – Anton
这和你一样工作说它会的,这对我的情况来说是完美的。谢谢! :)除了我没有制作字典,我把它留作多个继承类的对象,并简单地将Value属性变为动态类型 – DethoRhyne