【发布时间】:2010-04-29 13:47:21
【问题描述】:
我正在尝试使用泛型类型参数制作通用解析器,但我无法 100% 掌握这个概念
private bool TryParse<T>(XElement element, string attributeName, out T value) where T : struct
{
if (element.Attribute(attributeName) != null && !string.IsNullOrEmpty(element.Attribute(attributeName).Value))
{
string valueString = element.Attribute(attributeName).Value;
if (typeof(T) == typeof(int))
{
int valueInt;
if (int.TryParse(valueString, out valueInt))
{
value = valueInt;
return true;
}
}
else if (typeof(T) == typeof(bool))
{
bool valueBool;
if (bool.TryParse(valueString, out valueBool))
{
value = valueBool;
return true;
}
}
else
{
value = valueString;
return true;
}
}
return false;
}
正如您可能猜到的那样,代码无法编译,因为我无法将 int|bool|string 转换为 T(例如 value = valueInt)。感谢您的反馈,我什至可能无法做到这一点。使用 .NET 3.5
【问题讨论】:
-
哇,好问题。今晚当我有时间回到这个问题时,我将投票支持每一个可信的答案。
标签: c# .net parsing polymorphism