【发布时间】:2013-06-28 11:43:07
【问题描述】:
我写了下面的方法,满足以下要求-
- 输入是xmlnode和attributeName
- 如果找到并传递了关联的属性名称,则返回该值
-
如果传递的attributeName中没有值,它应该返回 -
3.1。对于 int -1 3.2.对于日期时间 DateTime.MinValue 3.3.对于字符串,空 3.4.对于布尔值,null
对于案例 3.4,以下方法失败。
public T AttributeValue<T>(XmlNode node, string attributeName)
{
var value = new object();
if (node.Attributes[attributeName] != null && !string.IsNullOrEmpty(node.Attributes[attributeName].Value))
{
value = node.Attributes[attributeName].Value;
}
else
{
if (typeof(T) == typeof(int))
value = -1;
else if (typeof(T) == typeof(DateTime))
value = DateTime.MinValue;
else if (typeof(T) == typeof(string))
value = null;
else if (typeof(T) == typeof(bool))
value = null;
}
return (T)Convert.ChangeType(value, typeof(T));
}
当把它改成
public System.Nullable<T> AttributeValue<T>(XmlNode node, string attributeName) where T : struct
{
var value = new object();
if (node.Attributes[attributeName] != null && !string.IsNullOrEmpty(node.Attributes[attributeName].Value))
{
value = node.Attributes[attributeName].Value;
}
else
{
if (typeof(T) == typeof(int))
value = -1;
else if (typeof(T) == typeof(DateTime))
value = DateTime.MinValue;
else if (typeof(T) == typeof(string))
return null;
else if (typeof(T) == typeof(bool))
return null;
}
return (T?)Convert.ChangeType(value, typeof(T));
}
字符串类型失败,即案例 3.3
期待一些帮助。
【问题讨论】:
-
如何调用第一组代码中的方法?您需要将其称为
AttributeValue<bool?>(...)如果您只调用AttributeValue<bool>(...),那么null不是bool的有效值。编辑:您的第二种情况失败,因为string不能用于System.Nullable<T>,因为string不是值类型结构。
标签: c# nullable generic-programming