我根据以下要求编写了下面的方法:
- 输入为xmlnode和attributeName
- 如果找到与传递的属性名称相关联的值,则返回该值
当传入的attributeName没有对应值时,应返回:
3.1. 对于int类型,返回-1 3.2. 对于DateTime类型,返回DateTime.MinValue 3.3. 对于String类型,返回null 3.4. 对于bool类型,返回null
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
不是值类型结构体。 - Chris Sinclair