Czy ktoś mający doświadczenie z C# ma pomysł jak rozwiązać poniższy problem? W skrócie:
*
GetValue<T> powinien zwrócić obiekt typu T utworzony ze stringa
* domyślny konwerter z
bool nie rozumie wyrażeń 0/1
* GetParam<bool> niestety wywołuje GetValue<T> (a nie specjalizację)
Czy w ogóle da się w C# zrobić taką specjalizację jak w C++?
Można to niby załatwić za pomocą refleksji czy choćby
if (typeof(T) == typeof(bool)), ale...
public static class Ext
{
public static T GetParam<T>(this XmlNode n, string name)
{
return GetParam<T>(n, name, default(T));
}
public static T GetParam<T>(this XmlNode n, string name, T def)
{
if (n["extra"] == null) return def;
if (n["extra"]["technique"] == null) return def;
foreach (XmlNode n2 in n["extra"]["technique"])
{
if (n2.Name == "param")
{
if (n2.Attributes["name"].Value == name)
{
return GetValue<T>(n2.InnerText);
}
}
}
return def;
}
public static T GetValue<T>(string s)
{
return (T)(s as IConvertible).ToType(typeof(T), CultureInfo.CurrentCulture);
}
public static bool GetValue(string s)
{
if (s.Trim() == "1" || s.Trim().ToLower() == "true") return true;
if (s.Trim() == "0" || s.Trim().ToLower() == "false") return false;
throw new Exception("Can't convert <" + s + "> to Boolean.");
}
}